在Python 3.2使用的HTMLParser [英] Using HTMLParser in Python 3.2
问题描述
我一直在使用的HTML解析器从网站报废数据和剥离HTML编码,而这样做。我知道不同的模块,如美丽的汤,而是决定走不依赖于外模块的路径。这里是Eloff提供的code code:地带HTML从Python中
I have been using HTML Parser to scrapping data from websites and stripping html coding whilst doing so. I'm aware of various modules such as Beautiful Soup, but decided to go down the path of not depending on "outside" modules. There is a code code supplied by Eloff: Strip HTML from strings in Python
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
它工作在Python 3.1。不过,我最近升级到Python 3.2.X,并发现我得到关于上文所写的HTML解析器code错误。
It works in Python 3.1. However, I recently upgraded to Python 3.2.x and have found I get errors regarding the HTML Parser code as written above.
我的第一个错误指向行:
My first error points to the line:
s.feed(html)
...和错误说...
... and the error says ...
AttributeError: 'MLStripper' object has no attribute 'strict'
因此,一些研究之后,我添加了严= true将顶线,使得它...
So, after a bit of research, I add "strict=True" to the top line, making it...
class MLStripper(HTMLParser, strict=True)
不过,我得到的新的错误:
However, I get the new error of:
TypeError: type() takes 1 or 3 arguments
要看看会发生什么,我删除了自我的说法,并在严=真......这给了错误左:
To see what would happen, I removed the "self" argument and left in the "strict=True"... which gave up the error:
NameError: global name 'self' is not defined
...我得到了我猜的猜测的感觉。
... and I got the "I'm guessing on guesses" feeling.
我不知道在第三个参数类MLStripper(HTMLParser的)
行会,在自
和严格= TRUE
;研究没有任何折腾启发。
I have no idea what the third argument in the class MLStripper(HTMLParser)
line would be, after self
and strict=True
; research didn't toss any enlightenment.
推荐答案
您是继承的HTMLParser
,但你是不是调用它的 __ init__
方法。您需要一行添加到您的 __ __的init
方法:
You're subclassing HTMLParser
, but you aren't calling its __init__
method. You need to add one line to your __init__
method:
def __init__(self):
super().__init__()
self.reset()
self.fed = []
此外,为Python 3,进口线是:
Also, for Python 3, the import line is:
from html.parser import HTMLParser
通过这些变化,一个简单的例子工程。不要更改类
行,这是不相关的。
With these changes, a simple example works. Don't change the class
line, that's not related.
这篇关于在Python 3.2使用的HTMLParser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!