给定以下带有三个a
标记的html:
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<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" id="link1">Elsie</a>,
<a class="lister__item cf lister__item--upsell lister__item--has-ribbon brand-highlight" id="link2">Lacie</a> and
<a id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
我想创建一个SoupStrainer实例,它可以精简html_doc
,过滤a
标记,其中class
属性包含“lister\uu item”。在
我可以这样做没有一个SoupStrainer,如下所示:
^{pr2}$如何用传递给BeautifulSoup
对象的parse_only
的SoupStrainer实例来模拟这一点?一、 e
strainer = SoupStrainer(lambda tag: tag.name=='a' and 'lister__item' in tag.get('class'))
soup = BeautifulSoup(html_doc, 'html.parser', parse_only=strainer)
# TypeError: <lambda>() takes 1 positional argument but 2 were given
不知道到底是怎么做的,但通过一些诡计很容易找到解决办法。通过打印所有
*args
,首先查看传递给lambda callable的内容:现在适应你的}:
^{pr2}$lambda
(区别在于一个是BeautifulSoup
类型,另一个是{soup
现在包含相同的结果:相关问题 更多 >
编程相关推荐