【问题标题】:Python Requests HTML - img src gets scraped with data:image/gif;base64Python 请求 HTML - img src 被数据刮掉:image/gif;base64
【发布时间】:2021-10-01 08:36:31
【问题描述】:

我尝试使用请求 html 抓取产品图片(不能使用 BeautifulSoup,因为它使用 JavaScript 动态加载)。

我从产品页面中找到并提取了图像src 属性,如下所示:

images = r.html.find('img.product-media-gallery__item-image')
for image in images:
    print(image.attrs["src"])

但输出看起来像this。我已经尝试用空白字符串替换小图像需要的字符串, 但是从图像源中根本没有任何内容被刮掉。

如何删除像素大小的图片,只保留有用的产品图片 URL?

【问题讨论】:

标签: python web-scraping python-requests-html


【解决方案1】:

这些像素大小的图像是实际图像的占位符。正如您所说,数据是使用 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)

【讨论】:

  • 天哪,非常感谢,它有效
  • @mistert1984 很高兴为您提供帮助!如果我的回答是正确的,请点赞并点击旁边的绿色复选标记✓ :)
  • 但是我现在应该如何只输出 url
  • @mistert1984 您可以在此代码末尾添加 for image in images: print(image['url']) 以打印所有 URL。
猜你喜欢
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
相关资源
最近更新 更多