python - Python 请求 HTML - img src 被数据刮掉:image/gif;base64
问题描述
我尝试使用请求 html 抓取产品图像(不能使用 BeautifulSoup,因为它使用 JavaScript 动态加载)。
我从产品页面中找到并提取了图像src
属性,如下所示:
images = r.html.find('img.product-media-gallery__item-image')
for image in images:
print(image.attrs["src"])
但输出看起来像这样。我已经尝试用空白字符串替换小图像需要的字符串,但是从图像源中根本没有刮掉任何东西。
我该怎么做才能删除像素大小的图像并只保留有用的产品图像 URL?
解决方案
这些像素大小的图像是实际图像的占位符。正如您所说,数据是使用 JavaScript 动态加载的,这是获取图像链接的唯一方法。您可以通过解析 HTML 数据并从那里获取 JSON 链接来做到这一点。
首先下载您的页面 HTML:
from requests import get
html_data = get("https://www.coolblue.nl/product/858330/sony-kd-65xh9505-2020.html").text
您可以使用正则表达式语句从 HTML 源代码中提取图像 JSON 数据,然后对 HTML 编码的字符进行转义:
import re
from html import unescape
decoded_html = unescape(re.search('<div class="product-media-gallery js-media-gallery"\s*data-component="(.*)"', html_data).groups()[0])
您现在可以将 JSON 加载到 python 字典中,如下所示:
from json import loads
json_data = loads(decoded_html)
然后简单地遍历 JSON,直到找到图像链接列表:
images = json_data[3]["options"]["images"]
print(images)
综上所述,脚本如下所示:
from requests import get
import re
from html import unescape
from json import loads
# Download the page
html_data = get("https://www.coolblue.nl/product/858330/sony-kd-65xh9505-2020.html").text
# Decode the HTML and get the JSON
decoded_html = unescape(re.search('<div class="product-media-gallery js-media-gallery"\s*data-component="(.*)"', html_data).groups()[0])
# Load it as a dictionary
json_data = loads(decoded_html)
# Get the image list
images = json_data[3]["options"]["images"]
print(images)
推荐阅读
- python - 在单线程上运行 Pybind11
- jxbrowser - JxBrowser 中的上下文菜单只显示一次
- reactjs - 如何让最简单的 Material UI Select 与 React 和 Typescript 一起使用?
- spring - 在 Spring Integration DSL 服务激活器中丢弃消息
- algorithm - 如果您在二维数组上进行二分搜索,matrix[mid/n][mid%n] 如何为您提供中间值?
- python - 在 Python 中将数据加载到训练集中
- ansible - Ansible - 当条件不适用于元任务时
- asp.net-mvc - 如何指定多个默认注销方案?
- reactjs - 如何修复吞吐量 5xx 错误请求 heroku
- ios - ViewPager 和 GooglePlacesAutocomplete 在 Expo 下的 React Native 中不能一起工作