Python 不使用正则表达式提取 HTML 标签属性
有没有办法用 urlib
、urllib2
或 BeautifulSoup
来提取 HTML 标签的属性呢?
比如说:
<a href="xyz" title="xyz">xyz</a>
获取 href=xyz, title=xyz
还有另一个讨论提到使用 正则表达式 来提取标签属性。
谢谢!
2 个回答
6
你为什么不试试HTMLParser模块呢?
可以像这样做:
import HTMLParser
import urllib
class parseTitle(HTMLParser.HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'a':
for names, values in attrs:
if name == 'href':
print value # or the code you need.
if name == 'title':
print value # or the code you need.
aparser = parseTitle()
u = urllib.open('http://stackoverflow.com') # change the address as you like
aparser.feed(u.read())
9
你可以使用BeautifulSoup这个工具来解析HTML网页。对于每一个标签,你可以用
In [111]: soup = BeautifulSoup.BeautifulSoup('<a href="xyz" title="xyz">xyz</a>')
In [112]: [tag.attrs for tag in soup.findAll('a')]
Out[112]: [[(u'href', u'xyz'), (u'title', u'xyz')]]