python提取没有正则表达式的HTML标记属性

时间:2011-08-21 21:57:38

标签: python html-parsing beautifulsoup

有没有办法使用urliburllib2BeautifulSoup来提取HTML标记属性?

例如:

<a href="xyz" title="xyz">xyz</a>

获取href=xyz, title=xyz

还有另一个讨论使用regular expressions

的主题

由于

2 个答案:

答案 0 :(得分:6)

您可以使用BeautifulSoup来解析HTML,并为每个<a>标记使用tag.attrs来读取属性:

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')]]

答案 1 :(得分:5)

为什么不尝试使用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())
相关问题