Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-美丽的汤-如何过滤提取的数据中的关键字?_Python_Beautifulsoup_Python Requests_Screen Scraping - Fatal编程技术网

Python-美丽的汤-如何过滤提取的数据中的关键字?

Python-美丽的汤-如何过滤提取的数据中的关键字?,python,beautifulsoup,python-requests,screen-scraping,Python,Beautifulsoup,Python Requests,Screen Scraping,我想使用Beautiful Soup和请求刮取网站的数据,我已经获得了我想要的数据,但现在我想过滤它: 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

我想使用Beautiful Soup和请求刮取网站的数据,我已经获得了我想要的数据,但现在我想过滤它:

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”?

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

例如:

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

result:  22222

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

例如:

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

result:  22222

假设
article.get(“数据变量代码”)
打印
11111222233333
, 您可以简单地使用
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)

假设
article.get(“数据变量代码”)
打印
11111222233333
, 您可以简单地使用
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)

你的问题有点模棱两可,因此有两个完全不同的答案都是正确的。你的问题有点模棱两可,因此有两个完全不同的答案都是正确的。我可能应该自己想出这个答案。哈哈,谢谢你的欢迎。如果有帮助的话,你应该接受这个作为你的答案:)也许我自己也应该想到这个哈哈,谢谢你的欢迎。如果有帮助,你应该接受这一点作为你的答案:)