[英]BeautifulSoup4 documentation example doesn't work
我是 BeautifulSoup4 的新手并且非常深入地学习它。 问题在于下一段代码(我在https://www.crummy.com/software/BeautifulSoup/bs4/doc/页面上的文档中找到了它,关于函数定义的文章):
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id') (A)
soup.find_all(has_class_but_no_id)
我希望得到这样的结果(见文档):
# [<p class="title"><b>The Dormouse's story</b></p>,
# <p class="story">Once upon a time there were...</p>, (B)
# <p class="story">...</p>]
但我得到了下一个结果:
[<p class="title"><b>The Dormouse's story</b></p>, <p class="story">Once
upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>, <p class="story">...</p>]
我检查了文档,发现只有.has_attr方法已被弃用。 并且没有更多细节。 如何更改初始代码 (A) 以获得预期结果 (B)? 任何人都可以帮助解决这个问题吗? 谢谢。
有用。 您必须注意,列表中的第二个结果没有检查内部标签(子标签)中的相同条件。 因此,包装<p class="story">
已满足条件并已与其所有内容一起放入结果列表中。
这个结果列表:
[<p class="title"><b>The Dormouse's story</b></p>,
-------------------------
<p class="story">Once
upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>,
-------------------------
<p class="story">...</p>]
包含三个标签,每个项目都有“class”属性,没有“id”属性。
Doc 说:
这个函数只选择'p'标签。它不选择'a'标签,因为这些标签定义了“class”和“id”。 它不会选择像“html”和“title”这样的标签,因为这些标签没有定义“class”。
soup.find_all(has_class_but_no_id)
# [<p class="title"><b>The Dormouse's story</b></p>,
# <p class="story">Once upon a time there were...</p>,
# <p class="story">...</p>]
不清楚,它导致人们期望没有任何标签的结果。他们应该更改陈述或示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.