python - Requests 只获取网站源代码的一部分
问题描述
我正在尝试抓取 target.com,它似乎只解析了网站的一部分而没有产品(主要部分)。我的代码非常适合沃尔玛,但这个网站不...
我的代码:
res = requests.get(f'https://www.target.com/s?searchTerm=mask')
print(res) # Prints 200
try:
res.raise_for_status()
except requests.exceptions.HTTPError as e:
print('Connection Error') # In case the connection fails
else:
soup = BeautifulSoup(res.text, "html.parser")
print(soup.find_all('li', class_='Col-favj32-0 diyyNr h-padding-a-none h-display-flex', limit = 5))
如果我打印 soup.prettify() 它会打印网站的一部分,但没有产品......我知道它可以与 Selenium 一起使用,我尝试过,但需要它在没有它的情况下工作。
解决方案
您在页面上看到的有关产品的数据是从外部 URL 加载的。您可以使用requests
/ json
modules 来加载这些数据。
例如:
import json
import requests
kw = 'mask'
url = 'https://redsky.target.com/v2/plp/search/?channel=web&count=96&keyword={kw}&offset=0&pricing_store_id=3991&key=ff457966e64d5e877fdbad070f276d18ecec4a01'
data = requests.get(url.format(kw=kw)).json()
# uncomment this to print all data;
# print(json.dumps(data, indent=4))
# print some data to screen
for i in data['search_response']['items']['Item']:
print('{:<60} {}'.format(i['title'], i['price']['formatted_current_price']))
印刷:
2pk Adult Fabric Face Mask $4.00
ICU Non Medical Face Mask 20ct $15.99
Adult 2pk Fabric Face Mask - Colors May Vary $5.00
Kids' 2pk Fabric Face Masks - Colors May Vary $5.00
Intco Non-medical Disposable Face Mask - 10ct $8.99
Cetaphil Pro Derma Control Purifying Clay Mask - 3oz $15.99
Jurassic World Velociraptor "Blue" Chomp 'N Roar Mask $29.99
Pixi DetoxifEYE Facial Treatment - 60ct $24.00
...and so on.
推荐阅读
- powershell - 使用 powershell 读取文本文件并捕获数组中的内容
- python - 如何在熊猫中列出最高相关对(一个规范列与所有其他列)?
- python - 在无限循环期间更新kivy解析器应用程序中的标签
- snowflake-cloud-data-platform - 使用 Snowflake UDF 查询变更跟踪表元数据
- javascript - nginx和nestjs认证部分之间的错误
- r - 运算符如何不使用 is.numeric
- html - Windows 10 是否预装了 CSS 和 html?如果没有,我该如何安装它们
- solr - 在 Sitecore 索引管理器中重建 Solr 索引不会更新 Solr 管理中的文档数
- c# - 无法使用 Win32 API (Bluetoothapis.h) 打开/关闭蓝牙无线电设置
- c# - 如何阻止 Visual Studio 恢复旧的输出文件?