python - 如何在请求中获取页面标题

标签 python html html-parsing

在 Requests 中获取页面标题的最简单方法是什么?

r = requests.get('http://www.imdb.com/title/tt0108778/')
# ? r.title
Friends (TV Series 1994–2004) - IMDb

最佳答案

您需要一个 HTML 解析器来解析 HTML 响应并获取 title 标记的文本:

示例使用 lxml.html :

>>> import requests
>>> from lxml.html import fromstring
>>> r = requests.get('http://www.imdb.com/title/tt0108778/')
>>> tree = fromstring(r.content)
>>> tree.findtext('.//title')
u'Friends (TV Series 1994\u20132004) - IMDb'

当然还有其他选项,例如 mechanize图书馆:

>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open('http://www.imdb.com/title/tt0108778/')
>>> br.title()
'Friends (TV Series 1994\xe2\x80\x932004) - IMDb'

选择什么选项取决于您接下来要做什么:解析页面以获取更多数据,或者,您可能希望与其进行交互:单击按钮、提交表单、跟踪链接等。

此外,您可能希望使用 IMDB 提供的 API,而不是继续进行 HTML 解析,请参阅:

IMDbPY 包的用法示例:

>>> from imdb import IMDb
>>> ia = IMDb()
>>> movie = ia.get_movie('0108778')
>>> movie['title']
u'Friends'
>>> movie['series years']
u'1994-2004'

关于python - 如何在请求中获取页面标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26812470/

相关文章:

php - 我似乎无法在 header.php 上动摇验证错误(如 "Stray start tag html")

python - 将循环的结果分配给 Python 中的变量

python - Python中的socket编程——实际的远程端口

python - 如何同步python线程的开始时间?

objective-c - NSCocoaErrorDomain 问题。

java - 使用 JSoup 提取表数据

python - 在函数中引用 DataFrame 名称(pandas、python3)

javascript - DIV 中的长 UL 列表,自动滚动到 LI 元素

javascript - HTML选择框,通过javascript删除选项出现 'None'选项

html - 我看不到整个 html 元素