题
我想获取我打开使用的urllib2一个网页的标题。什么是做到这一点,来解析HTML和寻找我需要的东西(现在只有 - 标签,但可能需要更多的未来)的最佳方式。
是否有此目的的优良解析LIB?
解决方案
是我建议 BeautifulSoup
如果你得到的称号,它只是:
soup = BeautifulSoup(html)
myTitle = soup.html.head.title
或
myTitle = soup('title')
这是非常稳健,将解析HTML,无论它是多么混乱。
其他提示
尝试美丽的汤:
url = 'http://www.example.com'
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
title = soup.html.head.title
print title.contents
你们怎么导入整个额外库一个任务。没有正则表达式?不是为的urllib不是BS4或机甲这是第三方的要求?与标准库做解析HTML和匹配字符串,然后用重或whateves分裂'>'
'<'
。
N=(len(html))
for a in html(N):
if '<title>' in a:
Title=(str(a))
这就是蟒2我想,可以剥离它
使用美丽的汤。
html = urllib2.urlopen("...").read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
print soup.title.string
不隶属于 StackOverflow