首页 > python爬虫中,使用HTMLParser如何解析获取多个标签中的文本

python爬虫中,使用HTMLParser如何解析获取多个标签中的文本

使用python进行网络爬虫编写时,如何使用HTMLParser解析获取到html文档中多个标签中的文本:
例如:
<a标签>text1
<span标签>text2</span标签>
text3
<span标签>text4</span标签>
text5
</a标签>
使用handle_data函数进行处理时,只能获取到标签中的文本,即text1,text2,text4,
其他两个text3和text5无法获取。

求大师们指教!


from HTMLParser import *


class MyParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.links = []
        self.flag = 0

    def handle_data(self, data):
        data = data.strip()
        if data and self.flag:
            print "handle_data", data

    def handle_starttag(self, tag, attrs):
        self.flag = 0

    def handle_endtag(self, tag):
        tag = tag.strip()
        if tag == "span标签":
            self.flag = 1

handle_starttag每遇见一个以"<"开始的tag回调一次,handle_endtag每遇见一个"</"标识的结束时回调一次,你的text3和text5位于结束标记之后,因此要自己手动用flag标记下,然后在handle_data里处理对应的数据

【热门文章】
【热门文章】