Python 获取 <title>
我想用urllib2来获取我打开的网页的标题。有什么好的方法可以做到这一点呢?我需要解析网页的HTML,找到我想要的内容(现在只需要
有没有什么好的解析库可以用来实现这个目的?
4 个回答
0
使用 Beautiful Soup 这个工具。
html = urllib2.urlopen("...").read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
print soup.title.string
5
试试这个叫做 Beautiful Soup 的工具:
url = 'http://www.example.com'
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
title = soup.html.head.title
print title.contents
9
是的,我推荐使用 BeautifulSoup
如果你想获取网页的标题,可以简单地这样做:
soup = BeautifulSoup(html)
myTitle = soup.html.head.title
或者
myTitle = soup('title')
这个内容来自于 官方文档
它非常强大,可以处理各种杂乱的HTML代码。