首页 > 解决方案 > 刮沃尔玛搜索结果python

问题描述

我正在尝试在沃尔玛上抓取搜索结果。

例如,让我们去域“ https://www.walmart.com/search/?query=coffee%20machine

并尝试仅从具有类名的元素中提取文本search-product-result,全部在 python 中。

我试过selenium了,我被要求验证我的身份。我试过requests了,我从沃尔玛得到了禁止页面。我已经尝试过其他库,但我的想法已经不多了。有什么建议吗?

标签: pythonpython-3.xseleniumweb-scrapingpython-requests

解决方案


此 URL 中的数据正在由 JavaScript 加载。所以beautifulsoup在这种情况下不起作用。

但是,页面显示的数据在其 HTML 代码中以 JSON 字符串的形式出现在<script>标签内。id=searchContent

我已经<script>从 HTML 代码中提取了它,进行了一些剥离并将文本转换为 JSON。您可以从该 JSON 中提取所需的任何数据。

这是打印搜索结果的产品 ID 的代码。

from bs4 import BeautifulSoup
import requests
import json

headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"}
url = 'https://www.walmart.com/search?query=coffee%20machine'

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'lxml')
s = str(soup.find('script', {'id': 'searchContent'}))
s = s.strip('<script id="searchContent" type="application/json"></script>')
j = json.loads(s)
x = j['searchContent']['preso']['items']


for i in x:
    print(i['productId'])

输出产品 ID。

2RYLQXVZ80E8
7EYUEQ82RMBP
7A3VDQNS5R36
22GRP3PGSY4A
238DLP3R0M3W
52NMIX2M8SC5
1R4H630LRNSE
.
.
.

推荐阅读