使用组和请求提取数据

2024-09-29 23:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从Unsplash下载狗的图片。但是,当我使用beautifulsou访问div时,只有一些循环显示div类中的URL。有什么办法解决吗?你知道吗

我的代码如下:


import requests
from bs4 import BeautifulSoup as soup
import os

res = requests.get('https://unsplash.com/s/photos/shiba')

doggo_soup = soup(res.text,'html.parser')

containers = doggo_soup.findAll('div',{'class','IEpfq'})

if not os.path.exists('shiba'):
    os.makedirs('shiba')

os.chdir('shiba')

index = 1

for container in containers:
    img_tag = container.img
    source = requests.get(img_tag)
    with open('shiba-'+str(index)+'jpg','wb') as output:
        output.write(source.content)
<div class="_3oSvn IEpfq" style="padding-bottom:66.6667%"><img alt="short-coated white dog on field" class="_2zEKz" data-test="photo-grid-single-col-img" style="background-color:#060606"/></div>

当我在开发人员控制台上检查div类IEpfq时,所有div类IEpfq都包含图片的URL。你知道吗

但是,当我运行代码时,它只显示了第4张图片之后相同div类下的部分信息(没有URL)。(如以上输出所示)任何帮助都将不胜感激!你知道吗


Tags: 代码importdivurlimggetosas
2条回答

你的代码有几个问题,试试这个它对我有用。我添加了异常处理程序,以便在任何图像下载失败时继续该过程,而且您的代码不会在每次迭代时更新index计数器:

import requests
from bs4 import BeautifulSoup as soup
import os

res = requests.get('https://unsplash.com/s/photos/shiba')

doggo_soup = soup(res.text,'html.parser')

containers = doggo_soup.findAll('div',{'class','IEpfq'})

if not os.path.exists('shiba'):
    os.makedirs('shiba')

os.chdir('shiba')

index = 1

for container in containers:
    try:
        img_tag = container.img
        source = requests.get(img_tag.get('src'))
        with open('shiba-'+str(index)+'.jpg','wb') as output:
            output.write(source.content)
        index += 1
    except:
      pass

这是一个稍有改动的代码。它为我下载了20张照片。你知道吗

import requests
from bs4 import BeautifulSoup as soup
import os

res = requests.get('https://unsplash.com/s/photos/shiba')

doggo_soup = soup(res.text,'html.parser')

containers = doggo_soup.find_all('div',class_='_2BSIe _3pmDG')


if not os.path.exists('shiba'):
    os.makedirs('shiba', exist_ok=True)

index = 1

for container in containers:
    imgUrl = container.find('a')['href']
    source = requests.get(imgUrl)
    imageFile = open(os.path.join('shiba', os.path.basename(str(index) + '.jpg')), 'wb')
    for chunk in source.iter_content(1000000):
        imageFile.write(chunk)
    imageFile.close()
    index +=1

相关问题 更多 >

    热门问题