【问题标题】:Python - Beautiful Soup - How to filter the extracted data for keywords?Python - Beautiful Soup - 如何过滤提取的关键字数据?
【发布时间】:2019-08-08 07:29:27
【问题描述】:

我想使用 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

我怎样才能过滤这个,让它只返回“22222”?

【问题讨论】:

  • 您的问题有点模棱两可,因此两个完全不同的答案都是正确的。

标签: python beautifulsoup python-requests screen-scraping


【解决方案1】:

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

例如:

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

result:  22222

【讨论】:

    【解决方案2】:

    假设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)
    

    【讨论】:

    • 应该是我自己想出来的哈哈,非常感谢
    • 欢迎您。如果它帮助你应该接受这个作为你的答案:)
    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多