将SoupStrainer与lambda表达式一起使用

时间:2017-09-14 18:15:38

标签: python python-3.x beautifulsoup

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

我想创建一个减少html_doc的SoupStrainer实例,过滤a标记,其中class属性包含'lister__item'。

我可以在没有SoupStrainer的情况下执行此操作,如下所示:

soup = BeautifulSoup(html_doc, 'html.parser')
soup.find_all(lambda tag: tag.name=='a' and 'lister__item' in tag.get('class'))

如何使用传递给parse_only对象的BeautifulSoup的SoupStrainer实例来模仿这个?即。

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

1 个答案:

答案 0 :(得分:2)

不知道究竟做了什么,但很容易通过一些棘手的方式获得解决方案。通过打印所有*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类型,另一个类型为element.Tag

strainer = bs4.SoupStrainer(lambda tag_name, d: tag_name == 'a' and 'lister__item' in d['class'])
soup = bs4.BeautifulSoup(html_doc, 'html.parser', parse_only=strainer)

soup现在包含相同的结果:

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