使用python 3和beautifulsoup从amazon上抓取图像

使用python 3和beautifulsoup从amazon上抓取图像,python,web-scraping,amazon,Python,Web Scraping,Amazon,我需要从亚马逊的产品页面上抓取主图像。 我将ASIN存储到一个列表中,并使用for循环构建每个产品页面。 我想把图像刮下来,但不行。我尝试使用以下代码: #declare a session object session = HTMLSession() #ignore warnings if not sys.warnoptions: warnings.simplefilter("ignore") urls = ['https://www.amazon.it/gp/bestseller

我需要从亚马逊的产品页面上抓取主图像。 我将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)

代码示例以查看页面上的“所有”img

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


    soup = BeautifulSoup(resp1, "html.parser")
    for i in soup.find_all("img"):
        print(i)

问题在于,图像是以动态方式加载的;通过查看页面,多亏了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

因此,您可以根据自己的需要应用这些方法,我认为这就是改进代码所需的全部。

当我转到findall()收集的第一页时,我没有看到任何landingImage id项。你在找这张照片吗。我看到的标签是:class=“a-dynamic-image-stretch-vertical-frontImage”id=“imgBlkFront”。我可以通过img项目在find_all循环中看到它。最好收集到一个列表中,然后再次使用re进行精简。它会更慢,但更稳定,因为Amz不喜欢刮削。是的,这就是我正在搜索的刮削图像。但是你做得怎么样?你能发布代码吗?但我总是得到相同的图像,有可能吗?