2

我可以将这两个块合并为一个:

编辑:除了像 Yacoby 在答案中所做的那样组合循环之外的任何其他方法。

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

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

我也可以将多个块合二为一:

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()

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

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

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

for tag in soup.findAll(class="noprint"):
    tag.extract()
4

4 回答 4

8

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

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

但是你可能最好先构建一个标签列表,然后对其进行迭代:

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

for tag in tags:
    tag.extract()

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

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

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

for tag in soup.findAll(id=lambda value: value in ['footer', 'content', 'links']):
    tag.extract()
于 2009-12-01T10:41:37.120 回答
5

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

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

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

for tag in soup.findAll(attrs={'class': 'noprint'}):
    tag.extract()
于 2009-12-01T10:05:26.690 回答
0

您问题第二部分的答案就文档

按 CSS 类搜索

attrs 参数将是一个非常晦涩的功能,如果它不是为了一件事:CSS。搜索具有特定 CSS 类的标签非常有用,但 CSS 属性的名称 class 也是 Python 的保留字。

您可以使用 soup.find("tagName", { "class" : "cssClass" }) 按 CSS 类进行搜索,但对于这种常见操作而言,代码量很大。相反,您可以为 attrs 传递一个字符串而不是字典。该字符串将用于限制 CSS 类。

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("""Bob's <b>Bold</b> Barbeque Sauce now available in 
                   <b class="hickory">Hickory</b> and <b class="lime">Lime</a>""")

soup.find("b", { "class" : "lime" })
# <b class="lime">Lime</b>

soup.find("b", "hickory")
# <b class="hickory">Hickory</b>
于 2009-12-01T10:09:45.690 回答
0
links = soup.find_all('a',class_='external') ,we can pass class_ to filter based on class values

from bs4 import BeautifulSoup
from urllib.request import urlopen

with urlopen('http://www.espncricinfo.com/') as f:
    raw_data= f.read()
    soup= BeautifulSoup(raw_data,'lxml')
    # print(soup)
    links = soup.find_all('a',class_='external')
    for link in links:
        print(link)
于 2018-01-26T17:53:42.807 回答