在lambda表达式中使用SoupStrainer

2024-10-03 11:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

给定以下带有三个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

Tags: andthe标记iddoctitlehtmltag
1条回答
网友
1楼 · 发布于 2024-10-03 11:20:34

不知道到底是怎么做的,但通过一些诡计很容易找到解决办法。通过打印所有*args,首先查看传递给lambda callable的内容:

strainer = bs4.SoupStrainer(lambda *args: print(args))
soup = bs4.BeautifulSoup(html_doc, 'html.parser', parse_only=strainer)
('html', {})
('head', {})
('title', {})
('body', {})
('p', {'class': 'title'})
('b', {})
('p', {'class': 'story'})
('a', {'class': 'sister', 'id': 'link1'})
('a', {'class': 'lister__item cf lister__item upsell lister__item has-ribbon brand-highlight', 'id': 'link2'})
('a', {'class': 'sister', 'id': 'link3'})
('p', {'class': 'story'})

现在适应你的lambda(区别在于一个是BeautifulSoup类型,另一个是{}:

^{pr2}$

soup现在包含相同的结果:

>>> soup
<a class="lister__item cf lister__item upsell lister__item has-ribbon brand-highlight" id="link2">Lacie</a>

相关问题 更多 >