如何使用Beautiful Soup获取网页图片?

问题描述 投票:0回答:1

我尝试用以下方式保存图片:

res=requests.get(url,headers=headers)
bs=BeautifulSoup(res.content,"html.parser")
images=bs.find_all("img")
for i,img in enumerate(images):
    try:
        img_url=img['src']
        print(img_url)
        if img_url[-1]=="g":
            res=requests.get(img_url)
            f=open(f"{name}/image_{i}.jpg","wb")
            f.write(res.content)
    except Exception as e:
        print(e)

但是有些图片没有保存,打印出来的

src
结果如下:

'src'
'src'
'src'

我猜是因为加载需要一段时间,我该怎么办?

python web-scraping beautifulsoup python-requests web-crawler
1个回答
0
投票

这里的问题是图像在进入视图时是延迟加载的。因此,有多种选择可以实现您的目标:

选项#1

使用

selenium
模仿浏览器,自动滚动并呈现完整源代码 -> similar topic exmaple

选项#2

更简单,使用您的模块并检查网站上包含您的信息的脚本内容 - 这是针对主要产品及其四个图像:

data = json.loads(
        BeautifulSoup(
            res.content,
            "html.parser"
        ).select_one('script[type="application/ld+json"]').text
    )

除了访问属性:

KeyError: [attr] - 当标签在 问题没有定义 attr 属性。最常见的错误是 KeyError: 'href' 和 KeyError: 'class'。使用 tag.get('attr') 如果你是 不确定是否定义了 attr,就像使用 Python 字典一样。

例子

import requests, json
from bs4 import BeautifulSoup
url='https://www.farfetch.com/uk/shopping/men/burberry-check-print-stretch-cotton-shirt-item-19844301.aspx'
res=requests.get(url, headers = {'user-agent':'some agent'})

data = json.loads(
            BeautifulSoup(
                res.content,
                "html.parser"
            ).select_one('script[type="application/ld+json"]').text
        )

输出

{'@context': 'https://schema.org',
 '@type': 'Product',
 'name': 'check print stretch-cotton shirt',
 'image': [{'@type': 'ImageObject',
   'contentUrl': 'https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44552233_1000.jpg',
   'description': 'Burberry check print stretch-cotton shirt'},
  {'@type': 'ImageObject',
   'contentUrl': 'https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44676163_1000.jpg',
   'description': 'Burberry check print stretch-cotton shirt'},
  {'@type': 'ImageObject',
   'contentUrl': 'https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44552234_1000.jpg',
   'description': 'Burberry check print stretch-cotton shirt'},
  {'@type': 'ImageObject',
   'contentUrl': 'https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44552232_1000.jpg',
   'description': 'Burberry check print stretch-cotton shirt'}],
 'productID': '19844301',
 'brand': {'@type': 'Brand', 'name': 'Burberry'},
 'offers': {'@type': 'Offer',
  'url': 'https://www.farfetch.com/shopping/men/burberry-check-print-stretch-cotton-shirt-item-19844301.aspx',
  'priceCurrency': 'GBP',
  'price': 470,
  'availability': 'https://schema.org/InStock',
  'itemCondition': 'https://schema.org/NewCondition'}}

只需迭代输出即可获取图片网址:

for img in data.get('image'):
    print(img.get('contentUrl'))

->

https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44552233_1000.jpg
https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44676163_1000.jpg
https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44552234_1000.jpg
https://cdn-images.farfetch-contents.com/19/84/43/01/19844301_44552232_1000.jpg
© www.soinside.com 2019 - 2024. All rights reserved.