python - 刮沃尔玛搜索结果python
问题描述
我正在尝试在沃尔玛上抓取搜索结果。
例如,让我们去域“ https://www.walmart.com/search/?query=coffee%20machine ”
并尝试仅从具有类名的元素中提取文本search-product-result
,全部在 python 中。
我试过selenium
了,我被要求验证我的身份。我试过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
.
.
.
推荐阅读
- python - QT:如何将程序生成的文件保存到用户的机器中
- youtube-api - YouTube - 用于创建广告的第三方广告 API?
- reactjs - 将 socket.io 集成到使用 REST 的 reactjs + redux
- c++ - 为什么函数 glViewport() 给我错误?
- python - multi_vowel_words 函数返回具有 3 个或更多连续元音的所有单词
- android - Kotlin DatePicker Pop-Up 在片段内不起作用:WindowManager$BadTokenException: Unable to add window -- token null is not valid;
- android - Kotlin,Android Studio:我无法让我的程序使用第二个适配器。列表视图
- css - Blazor WebAssembly 以不同的方式处理 css
- python - AutoPy - 点越界 (smooth_move)
- android - 无法将数据保存到 Firebase