【发布时间】:2015-02-04 13:22:00
【问题描述】:
我用python写了一些脚本,但从来没有真正接触过类。现在我需要一个,因为设置了一个 html 解析器(来自网络中的片段)。它工作正常,但缺少最后一个数据字符串。似乎该功能上次没有运行。
我的代码如下:
class MyHTMLParser(HTMLParser):
def __init__(self):
#reset
self.reset()
#options
self.strict = False
self.convert_charrefs= True
#create empty list for all my stored data
self.fed = []
def handle_data(self, data):
print ('D:', data) #as you might see in output of a run, string after last tag is not added, because function did obviously not run
self.fed.append('-'+data)
def get_data(self):
return ''.join(self.fed)
def process_description(desc):
s = MyHTMLParser()
s.feed(desc)
return s.get_data()
text_html='first <br />second<br />third'
text=process_description(text_html)
print (text)
输出:
D: first
D: second
-first -second
函数 process_description() 未完全处理 text_html 字符串。从输出中可以看出,handle_data() 函数未处理最后一个 html 标记之后的子字符串(“第三个”)。一定有一些语法错误。怎么了?
【问题讨论】:
-
能否请您澄清您的问题 - 究竟是什么问题?参见例如stackoverflow.com/help/mcve
-
问题已编辑,感谢您的建议。
标签: class python-3.x html-parsing