使用BeautifulSoup和Requests提取数据

亚伦

我想循环浏览并从Unsplash下载狗图片。但是,当我使用BeautifulSoup访问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)。(如上面的输出所示)任何帮助将不胜感激!

罪人养蜂

这是稍微更改的代码。它为我下载了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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 Requests 和 Beautifulsoup 抓取数据

使用BeautifulSoup和for循环提取数据

使用 Python 和 BeautifulSoup 提取 CME 数据

使用beautifulsoup和request提取json数据

使用Beautiful Soup和Requests提取数据

使用BeautifulSoup提取数据

使用BeautifulSoup和Requests从xml文件中打印数据

使用<script>和var从BeautifulSoup中提取数据

使用beautifulsoup和python从json中提取数据

使用 BeautifulSoup 解析和提取数据到 Pandas

使用BeautifulSoup提取网站数据

使用Beautifulsoup从网站提取数据

使用BeautifulSoup从tbody提取数据

使用BeautifulSoup和Requests和Pandas从<div>中的<span>抓取数据

Python-使用Beautifulsoup从网页提取数据

无法使用beautifulsoup提取表数据

使用beautifulsoup提取难以识别的数据

BeautifulSoup 使用 unicode 从 <script> 中提取数据

使用 BeautifulSoup 从评论中提取表格数据

如何使用BeautifulSoup,Requests和Python从HTML的特定表中抓取数据?

如何使用 BeautifulSoup 提取文本和列表

使用 beautifulSoup 和 Regex 提取文本

使用 BeautifulSoup 和 Python 提取 iframe

使用Selenium和BeautifulSoup提取iFrame内容

从多个URL中提取标题和表主体(使用beautifulsoup)到数据框

我不能使用不同的函数从beautifulsoup python中提取数据和过滤掉

如何解析呢?尝试使用BeautifulSoup和Python从非HTML网页提取数据

如何在Python和beautifulsoup中从CDATA中提取数据?

BeautifulSoup4 从 pre 样式中提取和选择数据