Dav*_*542 9 html python html-parsing
在请求中获取页面标题的最简单方法是什么?
r = requests.get('http://www.imdb.com/title/tt0108778/')
# ? r.title
Friends (TV Series 1994–2004) - IMDb
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 18
您需要一个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'
Run Code Online (Sandbox Code Playgroud)
当然还有其他选择,例如mechanize库:
>>> import mechanize
>>> br = mechanize.Browser()
>>> br.open('http://www.imdb.com/title/tt0108778/')
>>> br.title()
'Friends (TV Series 1994\xe2\x80\x932004) - IMDb'
Run Code Online (Sandbox Code Playgroud)
选择什么选项取决于您接下来要做什么:解析页面以获取更多数据,或者,您可能想要与之交互:单击按钮,提交表单,关注链接等.
此外,您可能希望使用提供的API IMDB,而不是转到HTML解析,请参阅:
IMDbPY包的示例用法:
>>> from imdb import IMDb
>>> ia = IMDb()
>>> movie = ia.get_movie('0108778')
>>> movie['title']
u'Friends'
>>> movie['series years']
u'1994-2004'
Run Code Online (Sandbox Code Playgroud)
Rah*_*wla 10
无需导入其他库。requests内置了此功能。
>>> hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}
>>> n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders)
>>> al = n.text
>>> al[al.find('<title>') + 7 : al.find('</title>')]
u'Friends (TV Series 1994\u20132004) - IMDb'
Run Code Online (Sandbox Code Playgroud)
ZN13评论后更新
>>> import re
>>> import requests
>>> n = requests.get('https://www.libsdl.org/release/SDL-1.2.15/docs/html/guideinputkeyboard.html')
>>> al = n.text
>>> d = re.search('<\W*title\W*(.*)</title', al, re.IGNORECASE)
>>> d.group(1)
u'Handling the Keyboard'
Run Code Online (Sandbox Code Playgroud)
这将适用于所有情况,无论<title>标签是否存在额外的非字母字符。
您可以使用beautifulsoup来解析HTML.
使用安装它 pip install beautifulsoup4
>>> import requests
>>> r = requests.get('http://www.imdb.com/title/tt0108778/')
>>> import bs4
>>> html = bs4.BeautifulSoup(r.text)
>>> html.title
<title>Friends (TV Series 1994–2004) - IMDb</title>
>>> html.title.text
u'Friends (TV Series 1994\u20132004) - IMDb'
Run Code Online (Sandbox Code Playgroud)
适合人类的 Pythonic HTML 解析。
from requests_html import HTMLSession
print(HTMLSession().get('http://www.imdb.com/title/tt0108778/').html.find('title', first=True).text)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20011 次 |
| 最近记录: |