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

day*_*mer 0 python beautifulsoup html-parsing

有没有办法使用urlib, urllib2BeautifulSoup提取HTML标签的属性?

例如:

<a href="xyz" title="xyz">xyz</a>
Run Code Online (Sandbox Code Playgroud)

得到 href=xyz, title=xyz

还有另一个讨论使用正则表达式的线程

谢谢

unu*_*tbu 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')]]
Run Code Online (Sandbox Code Playgroud)


Wal*_*ini 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())
Run Code Online (Sandbox Code Playgroud)