我可以将beautifulsoup中的两个'findAll'搜索块合并为一个吗?

Pri*_*lia 2 python beautifulsoup

我可以将这两个块组合成一个:

编辑:除了Yacoby在回答中组合循环之外的任何其他方法.

for tag in soup.findAll(['script', 'form']):
    tag.extract()

for tag in soup.findAll(id="footer"):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)

我也可以将多个块组合成一个:

for tag in soup.findAll(id="footer"):
    tag.extract()

for tag in soup.findAll(id="content"):
    tag.extract()

for tag in soup.findAll(id="links"):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)

或者可能有一些lambda表达式,我可以检查是否在数组或任何其他更简单的方法.

另外我如何找到属性类的标签,因为class是保留关键字:

编辑:这部分是由汤.findAll(attrs = {'class':'noprint'})解决的:

for tag in soup.findAll(class="noprint"):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)

小智 7

您可以将函数传递给.findall()这样:

soup.findAll(lambda tag: tag.name in ['script', 'form'] or tag['id'] == "footer")
Run Code Online (Sandbox Code Playgroud)

但是,首先构建一个标记列表然后迭代它可能会更好:

tags = soup.findAll(['script', 'form'])
tags.extend(soup.findAll(id="footer"))

for tag in tags:
    tag.extract()
Run Code Online (Sandbox Code Playgroud)

如果要过滤几个ids,可以使用:

for tag in soup.findAll(lambda tag: tag.has_key('id') and
                                    tag['id'] in ['footer', 'content', 'links']):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)

更具体的方法是将lambda分配给id参数:

for tag in soup.findAll(id=lambda value: value in ['footer', 'content', 'links']):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)


Yac*_*oby 5

我不知道 BeautifulSoup 是否可以做得更优雅,但你可以像这样合并两个循环:

for tag in soup.findAll(['script', 'form']) + soup.findAll(id="footer"):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)

你可以找到这样的类(文档):

for tag in soup.findAll(attrs={'class': 'noprint'}):
    tag.extract()
Run Code Online (Sandbox Code Playgroud)