Python: 使用HTML解析器提取特定数据

3
我开始使用Python中的HTMLParser从网站中提取数据。 我得到了我想要的一切,除了HTML标签内两个标签之间的文本。 以下是一个HTML标签的示例:
<a href="http://wold.livingsources.org/vocabulary/1" title="Swahili" class="Vocabulary">Swahili</a>

还有其他以开头的标签。它们具有其他属性和值,因此我不想拥有它们的数据:

<a href="http://wold.livingsources.org/contributor#schadebergthilo" title="Thilo Schadeberg" class="Contributor">Thilo Schadeberg</a>

这个标签是表格内的嵌入式标签。我不知道这与其他标签有什么区别。 我只想要一些名为'a'的标签中带有属性class="Vocabulary"的信息,我想要标签内的数据,在本例中应该是"Swahili"。 所以我做的是:

class AllLanguages(HTMLParser):
    '''
    classdocs
    '''
    #counter for the languages
    #countLanguages = 0
    def __init__(self):
        HTMLParser.__init__(self)
        self.inLink = False
        self.dataArray = []
        self.countLanguages = 0
        self.lasttag = None
        self.lastname = None
        self.lastvalue = None
        #self.text = ""


    def handle_starttag(self, tag, attr):
        #print "Encountered a start tag:", tag      
        if tag == 'a':
            for name, value in attr:
                if name == 'class' and value == 'Vocabulary':
                    self.countLanguages += 1
                    self.inLink = True
                    self.lasttag = tag
                    #self.lastname = name
                    #self.lastvalue = value
                    print self.lasttag
                    #print self.lastname
                    #print self.lastvalue
                    #return tag
                    print self.countLanguages




    def handle_endtag(self, tag):
        if tag == "a":
            self.inlink = False
            #print "".join(self.data)

    def handle_data(self, data):
        if self.lasttag == 'a' and self.inLink and data.strip():
            #self.dataArray.append(data)
            #
            print data

该程序会打印出所有包含在标签中的数据,但我只想要那些包含正确属性的标签中的数据。如何获取这些特定的数据?
2个回答

6
看起来您忘记了默认情况下在handle_starttag中设置self.inLink = False:
from HTMLParser import HTMLParser


class AllLanguages(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.inLink = False
        self.dataArray = []
        self.countLanguages = 0
        self.lasttag = None
        self.lastname = None
        self.lastvalue = None

    def handle_starttag(self, tag, attrs):
        self.inLink = False
        if tag == 'a':
            for name, value in attrs:
                if name == 'class' and value == 'Vocabulary':
                    self.countLanguages += 1
                    self.inLink = True
                    self.lasttag = tag

    def handle_endtag(self, tag):
        if tag == "a":
            self.inlink = False

    def handle_data(self, data):
        if self.lasttag == 'a' and self.inLink and data.strip():
            print data


parser = AllLanguages()
parser.feed("""
<html>
<head><title>Test</title></head>
<body>
<a href="http://wold.livingsources.org/vocabulary/1" title="Swahili" class="Vocabulary">Swahili</a>
<a href="http://wold.livingsources.org/contributor#schadebergthilo" title="Thilo Schadeberg" class="Contributor">Thilo Schadeberg</a>
<a href="http://wold.livingsources.org/vocabulary/2" title="English" class="Vocabulary">English</a>
<a href="http://wold.livingsources.org/vocabulary/2" title="Russian" class="Vocabulary">Russian</a>
</body>
</html>""")

输出:

Swahili
English
Russian

另外,也可以看一下以下内容:

希望这能帮到您。


非常感谢。我本来以为这只是一件小事 ;) 我也尝试了beautifulsoup,它也完美地运行了。 再次感谢您的帮助。 - IssnKissn
你有使用特殊解析器的推荐吗? 我需要将html文件中的数据写入xml文件。你会选择哪一个解析器?或者说其中一个解析器有什么优势? - IssnKissn
美丽汤(beautifulsoup)和lxml是不错的HTML解析器。lxml以其速度而闻名,而beautifulsoup非常方便但不支持XPath表达式。了解更多:http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/,https://dev59.com/EnA65IYBdhLWcg3w4C-j?rq=1,https://dev59.com/d2w15IYBdhLWcg3wntKh。 - alecxe
好的,我需要解析大量数据,因此beautifulsoup非常慢。但是我想我会尝试使用lxml。非常感谢。 - IssnKissn

3
你可以尝试使用HTQL (http://htql.net)。查询语句为:

"查找class为“Vocabulary”的'a'标签,并返回其中的数据"

<a (class='Vocabulary')>:tx 

Python代码如下:

import htql
a=htql.query(page, "<a (class='Vocabulary')>:tx")
print(a)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接