首页 > 解决方案 > 使用 python 3 和 beautifulsoup 从亚马逊抓取图像

问题描述

我需要从亚马逊的产品页面上抓取主图像。我将 ASIN 存储到一个列表中,并使用 for 循环构建每个产品页面。我正在尝试抓取图像,但我不能。我尝试使用此代码:

#declare a session object
session = HTMLSession()

#ignore warnings
if not sys.warnoptions:
    warnings.simplefilter("ignore")

urls = ['https://www.amazon.it/gp/bestsellers/apparel/', 'https://www.amazon.it/gp/bestsellers/electronics/', 'https://www.amazon.it/gp/bestsellers/books/']
asins = []
for url in urls:
    content = requests.get(url).content
    decoded_content = content.decode()
    asins = re.findall(r'/[^/]+/dp/([^\"?]+)', decoded_content)

#The ASIN Number will be between the dp/ and another /

for asin in asins:
    site = 'https://www.amazon.it/'
    start = 'dp/'
    end = '/'
    url = site + start + asin + end
    resp1 = requests.get(url).content

    soup = bsoup(resp1, "html.parser")
    body = soup.find("body")
    imgtag = soup.find("img", {"id":"landingImage"})
    imageurl = dict(imgtag.attrs)["src"]
    resp2 = request.urlopen(imaegurl)

标签: pythonweb-scrapingamazon

解决方案


问题是图像是动态加载的;检查页面,感谢BeautifulSoup 文档,给定产品,我能够抓取所有需要的图像。

获取给定链接的页面

我有一个存储数据的类,所以我将页面信息保存在实例中......

import urllib
from bs4 import BeautifulSoup

def take_page(self, url_page):
    req = urllib.request.Request(
        url_page,
        data=None
    )
    f = urllib.request.urlopen(req)
    page = f.read().decode('utf-8')
    self.page = page

刮图像

以下简单方法将返回最小尺寸的第一张图像

import json

def take_image(self):
    soup = BeautifulSoup(self.page, 'html.parser')
    img_div = soup.find(id="imgTagWrapperId")

    imgs_str = img_div.img.get('data-a-dynamic-image')  # a string in Json format

    # convert to a dictionary
    imgs_dict = json.loads(imgs_str)
    #each key in the dictionary is a link of an image, and the value shows the size (print all the dictionay to inspect)
    num_element = 0 
    first_link = list(imgs_dict.keys())[num_element]
    return first_link

因此,您可以将这些方法应用于您的需求,我认为这就是您改进代码所需的全部。


推荐阅读