我想循环浏览并从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] 删除。
我来说两句