使用爬蟲批量下載圖片


import requests
from bs4 import BeautifulSoup
import re
url='http://www.quanjing.com/'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3253.3 Safari/537.36'}
response=requests.get(url=url,headers=headers)
response.encoding='utf-8'
html=response.text
soup=BeautifulSoup(html,'html.parser')
imgs_src=soup.find_all('img',src=re.compile('^/image/2017index/'))
count=1
for i in imgs_src:
img_src='http://www.quanjing.com'+i['src']
response=requests.get(url=img_src,headers=headers,stream=True)
with open('D:/Python/img/'+str(count)+'.jpg','wb') as f:
#以字節流的方式寫入,每128個流遍歷一次,完成后為一張照片
for data in response.iter_content(128):
f.write(data)
print('第%d張照片下載完畢\n'%count)
count=count+1
print('照片下載完畢')

 

 



出現的兩個問題:
1.字符串與int型不能直接拼接,需要拼接前通過str()將int型轉成str
2.下載照片時,圖片時二進制文件,使用字節流將文件寫入


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM