Python - Beautiful Soup - 如何过滤提取的关键词数据?

Python - Beautiful Soup - How to filter the extracted data for keywords?

我想使用 Beautiful Soup 和 requests 抓取网站的数据,到目前为止我已经得到了我想要的数据,但现在我想过滤它:

from bs4 import BeautifulSoup
import requests
url = "website.com"
keyword = "22222"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'lxml')

for article in soup.find_all('a'):
    for a in article:
        if article.has_attr('data-variant-code'):
            print(article.get("data-variant-code"))

假设这会打印以下内容: 11111 22222 33333

我如何过滤它以便它只 returns 我是“22222”?

如果要打印由 space 分隔的字符串中的第二组字符,则可以使用 space 作为分隔符拆分字符串。这将为您提供一个字符串列表,然后访问列表的第二项。

例如:

print(article.get("data-variant-code").split(" ")[1])

result:  22222

假设 article.get("data-variant-code") 打印 11111, 22222, 33333, 您可以简单地使用 if 语句:

for article in soup.find_all('a'):
    for a in article:
        if article.has_attr('data-variant-code'):
           x = article.get("data-variant-code")
           if x == '22222':
               print(x)