我正在运行Python 3.5.1与Beautifulsoup4。
我现在有这个代码:
from bs4 import BeautifulSoup
import html5lib
class LinkFinder(BeautifulSoup):
def __init__(self):
super().__init__()
def handle_starttag(self, name, attrs):
print(name)
当我用下面的代码实例化类时:findmylink = LinkFinder()
,当我加载我的html与以下代码findmylink.feed("""<html><head><title>my name is good</title></head><body>hello world</body></html>""",'html5lib')
.
我在控制台中得到以下错误:
'NoneType' object is not callable
我实际上希望复制以下示例代码(在我的情况下,我希望使用Beautifulsoup而不是html.parser
)
from html.parser import HTMLParser
class LinkFinder(HTMLParser):
def __init__(self):
super().__init__()
def handle_starttag(self, tag, attrs):
print(tag)
当我通过以下代码重新实例化类时:findmylink = LinkFinder()
,当我用以下代码findmylink.feed("""<html><head><title>my name is good</title></head><body>hello world</body></html>""")
加载html时,我得到以下输出:
html
head
title
body
不确定为什么需要以这种不寻常的方式使用BeautifulSoup
。如果您只想递归地获取HTML树中所有元素的名称:
from bs4 import BeautifulSoup
data = """<html><head><title>my name is good</title></head><body>hello world</body></html>"""
soup = BeautifulSoup(data, "html5lib")
for elm in soup.find_all():
print(elm.name)
打印:
html
head
title
body
如果您想这样做,请更改实现以在初始化期间接受标记,并更改handle_starttag
以获取所有传递的参数:
class LinkFinder(BeautifulSoup):
def __init__(self, markup):
super().__init__(markup, 'html.parser')
def handle_starttag(self, name, namespace, nsprefix, attrs):
print(name)
初始化:
l = LinkFinder("""<html><head><title>my name is good</title></head><body>hello world</body></html>""")
打印出:
html
head
title
body
我很确定BeautifulSoup
类重载__getattr__
返回None
上未定义的属性,而不是提高AttributeError
;这就是导致错误的原因:
print(type(BeautifulSoup().feed))
NoneType
print(type(BeautifulSoup().feedededed))
NoneType
和,BeautifulSoup
不像HTMLParser
那样有feed
函数(它有一个_feed
,它用self.markup
调用builder
对象的底层feed
),所以你得到一个None
对象,你调用。