<p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>

[{'answer_id': 51240, 'author': 'Peter Hoffmann', 'author_id': 720, 'author_profile': 'https://Stackoverflow.com/users/720', 'pm_score': 7, 'selected': True, 'text': '<p>I\'ll always use <a href="http://lxml.de/" rel="nofollow noreferrer">lxml</a> for such tasks. You could use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow noreferrer">beautifulsoup</a> as well.</p>\n<pre><code>import lxml.html\nt = lxml.html.parse(url)\nprint(t.find(&quot;.//title&quot;).text)\n</code></pre>\n<p>EDIT based on comment:</p>\n<pre><code>from urllib2 import urlopen\nfrom lxml.html import parse\n\nurl = &quot;https://www.google.com&quot;\npage = urlopen(url)\np = parse(page)\nprint(p.find(&quot;.//title&quot;).text)\n</code></pre>\n'}, {'answer_id': 51242, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 4, 'selected': False, 'text': '<p>This is probably overkill for such a simple task, but if you plan to do more than that, then it\'s saner to start from these tools (mechanize, BeautifulSoup) because they are much easier to use than the alternatives (urllib to get content and regexen or some other parser to parse html)</p>\n<p>Links:\n<a href="http://crummy.com/software/BeautifulSoup" rel="nofollow noreferrer">BeautifulSoup</a>\n<a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow noreferrer">mechanize</a></p>\n<pre><code>#!/usr/bin/env python\n#coding:utf-8\n\nfrom bs4 import BeautifulSoup\nfrom mechanize import Browser\n\n#This retrieves the webpage content\nbr = Browser()\nres = br.open(&quot;https://www.google.com/&quot;)\ndata = res.get_data() \n\n#This parses the content\nsoup = BeautifulSoup(data)\ntitle = soup.find(\'title\')\n\n#This outputs the content :)\nprint title.renderContents()\n</code></pre>\n'}, {'answer_id': 51263, 'author': 'codeape', 'author_id': 3571, 'author_profile': 'https://Stackoverflow.com/users/3571', 'pm_score': 4, 'selected': False, 'text': '<p>The mechanize Browser object has a title() method. So the code from <a href="https://stackoverflow.com/questions/51233/how-can-i-retrieve-the-page-title-of-a-webpage-using-python#51242">this post</a> can be rewritten as:</p>\n\n<pre><code>from mechanize import Browser\nbr = Browser()\nbr.open("http://www.google.com/")\nprint br.title()\n</code></pre>\n'}, {'answer_id': 51550, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 7, 'selected': False, 'text': '<p>Here\'s a simplified version of <a href="https://stackoverflow.com/a/51242/4279">@Vinko Vrsalovic\'s answer</a>:</p>\n\n<pre><code>import urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(urllib2.urlopen("https://www.google.com"))\nprint soup.title.string\n</code></pre>\n\n<p>NOTE:</p>\n\n<ul>\n<li><p><em>soup.title</em> finds the first <em>title</em> element <strong>anywhere</strong> in the html document</p></li>\n<li><p><em>title.string</em> assumes it has only <strong>one</strong> child node, and that child node is a <strong>string</strong></p></li>\n</ul>\n\n<p>For <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer">beautifulsoup 4.x</a>, use different import:</p>\n\n<pre><code>from bs4 import BeautifulSoup\n</code></pre>\n'}, {'answer_id': 17123979, 'author': 'Sai Kiriti Badam', 'author_id': 2182787, 'author_profile': 'https://Stackoverflow.com/users/2182787', 'pm_score': 2, 'selected': False, 'text': "<p><code>soup.title.string</code> actually returns a unicode string.\nTo convert that into normal string, you need to do\n<code>string=string.encode('ascii','ignore')</code></p>\n"}, {'answer_id': 36650753, 'author': 'Finn', 'author_id': 4248511, 'author_profile': 'https://Stackoverflow.com/users/4248511', 'pm_score': 4, 'selected': False, 'text': '<p>Using <a href="https://docs.python.org/3.4/library/html.parser.html" rel="noreferrer">HTMLParser</a>:</p>\n<pre><code>from urllib.request import urlopen\nfrom html.parser import HTMLParser\n\n\nclass TitleParser(HTMLParser):\n    def __init__(self):\n        HTMLParser.__init__(self)\n        self.match = False\n        self.title = \'\'\n\n    def handle_starttag(self, tag, attributes):\n        self.match = tag == \'title\'\n\n    def handle_data(self, data):\n        if self.match:\n            self.title = data\n            self.match = False\n\nurl = &quot;http://example.com/&quot;\nhtml_string = str(urlopen(url).read())\n\nparser = TitleParser()\nparser.feed(html_string)\nprint(parser.title)  # prints: Example Domain\n</code></pre>\n'}, {'answer_id': 41958005, 'author': 'Rahul Chawla', 'author_id': 6775799, 'author_profile': 'https://Stackoverflow.com/users/6775799', 'pm_score': 5, 'selected': False, 'text': "<p>No need to import other libraries. Request has this functionality in-built.</p>\n\n<pre><code>&gt;&gt; hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}\n&gt;&gt;&gt; n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders)\n&gt;&gt;&gt; al = n.text\n&gt;&gt;&gt; al[al.find('&lt;title&gt;') + 7 : al.find('&lt;/title&gt;')]\nu'Friends (TV Series 1994\\u20132004) - IMDb' \n</code></pre>\n"}, {'answer_id': 44697410, 'author': 'Finn', 'author_id': 4248511, 'author_profile': 'https://Stackoverflow.com/users/4248511', 'pm_score': 3, 'selected': False, 'text': "<p>Using regular expressions</p>\n\n<pre><code>import re\nmatch = re.search('&lt;title&gt;(.*?)&lt;/title&gt;', raw_html)\ntitle = match.group(1) if match else 'No title'\n</code></pre>\n"}, {'answer_id': 47880739, 'author': 'Ricky Wilson', 'author_id': 2433063, 'author_profile': 'https://Stackoverflow.com/users/2433063', 'pm_score': 2, 'selected': False, 'text': "<p>Here is a fault tolerant <code>HTMLParser</code> implementation.<br>\nYou can throw pretty much anything at <code>get_title()</code> without it breaking, If anything unexpected happens\n<code>get_title()</code> will return <code>None</code>.<br>\nWhen <code>Parser()</code> downloads the page it encodes it to <code>ASCII</code>\nregardless of the charset used in the page ignoring any errors.\nIt would be trivial to change <code>to_ascii()</code> to convert the data into <code>UTF-8</code> or any other encoding. Just add an encoding argument and rename the function to something like <code>to_encoding()</code>.<br>\nBy default <code>HTMLParser()</code> will break on broken html, it will even break on trivial things like mismatched tags. To prevent this behavior I replaced <code>HTMLParser()</code>'s error method with a function that will ignore the errors.</p>\n\n<pre><code>#-*-coding:utf8;-*-\n#qpy:3\n#qpy:console\n\n''' \nExtract the title from a web page using\nthe standard lib.\n'''\n\nfrom html.parser import HTMLParser\nfrom urllib.request import urlopen\nimport urllib\n\ndef error_callback(*_, **__):\n    pass\n\ndef is_string(data):\n    return isinstance(data, str)\n\ndef is_bytes(data):\n    return isinstance(data, bytes)\n\ndef to_ascii(data):\n    if is_string(data):\n        data = data.encode('ascii', errors='ignore')\n    elif is_bytes(data):\n        data = data.decode('ascii', errors='ignore')\n    else:\n        data = str(data).encode('ascii', errors='ignore')\n    return data\n\n\nclass Parser(HTMLParser):\n    def __init__(self, url):\n        self.title = None\n        self.rec = False\n        HTMLParser.__init__(self)\n        try:\n            self.feed(to_ascii(urlopen(url).read()))\n        except urllib.error.HTTPError:\n            return\n        except urllib.error.URLError:\n            return\n        except ValueError:\n            return\n\n        self.rec = False\n        self.error = error_callback\n\n    def handle_starttag(self, tag, attrs):\n        if tag == 'title':\n            self.rec = True\n\n    def handle_data(self, data):\n        if self.rec:\n            self.title = data\n\n    def handle_endtag(self, tag):\n        if tag == 'title':\n            self.rec = False\n\n\ndef get_title(url):\n    return Parser(url).title\n\nprint(get_title('http://www.google.com'))\n</code></pre>\n"}, {'answer_id': 55968979, 'author': 'markling', 'author_id': 2455413, 'author_profile': 'https://Stackoverflow.com/users/2455413', 'pm_score': 0, 'selected': False, 'text': '<p>Using lxml...</p>\n\n<p>Getting it from page meta tagged according to the Facebook opengraph protocol:</p>\n\n<pre><code>import lxml.html.parse\nhtml_doc = lxml.html.parse(some_url)\n\nt = html_doc.xpath(\'//meta[@property="og:title"]/@content\')[0]\n</code></pre>\n\n<p>or using .xpath with lxml:</p>\n\n<pre><code>t = html_doc.xpath(".//title")[0].text\n</code></pre>\n'}, {'answer_id': 56416767, 'author': 'QHarr', 'author_id': 6241235, 'author_profile': 'https://Stackoverflow.com/users/6241235', 'pm_score': 3, 'selected': False, 'text': "<p>Use soup.select_one to target title tag</p>\n\n<pre><code>import requests\nfrom bs4 import BeautifulSoup as bs\n\nr = requests.get('url')\nsoup = bs(r.content, 'lxml')\nprint(soup.select_one('title').text)\n</code></pre>\n"}, {'answer_id': 66234986, 'author': 'S Habeeb Ullah', 'author_id': 12282050, 'author_profile': 'https://Stackoverflow.com/users/12282050', 'pm_score': 2, 'selected': False, 'text': "<p>In Python3, we can call method <code>urlopen</code> from <code>urllib.request</code> and <code>BeautifulSoup</code> from <code>bs4</code> library to fetch the page title.</p>\n<pre><code>from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nhtml = urlopen(&quot;https://www.google.com&quot;)\nsoup = BeautifulSoup(html, 'lxml')\nprint(soup.title.string)\n</code></pre>\n<p>Here we are using the most efficient parser 'lxml'.</p>\n"}]
['https://Stackoverflow.com/questions/51233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2386/']