新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何使用python批量下載圖片-創(chuàng)新互聯(lián)
如何使用python批量下載圖片?這個問題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純?nèi)容,讓我們一起來看看吧!
使用環(huán)境:python3+pycharm+requests+re+BeatifulSoup+json
步驟:
1、然后找到你需要下載圖片的網(wǎng)站。
2、找到需要下載的圖片,在搜索界面查看源碼,發(fā)現(xiàn)這個和前面的分析如出一轍,它的圖片id藏在js里面。我們只需通過正則解析。拿到id然后拼湊url即可完成所有圖片地址。
3、我們嘗試能不能獲得一個簡單通用的url地址。
代碼與總結(jié)
import requests from urllib import parse from bs4 import BeautifulSoup import re import json header = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'Cookie': 'wluuid=66; ', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Accept-encoding': 'gzip, deflate, br', 'Accept-language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0', 'connection': 'keep-alive' , 'Host': 'stock.tuchong.com', 'Upgrade-Insecure-Requests': '1' } def mkdir(path): import os# 引入模塊 path = path.strip()# 去除首位空格 path = path.rstrip("\\") # 去除尾部 \ 符號 isExists = os.path.exists(path) # 判斷路徑是否存在 # 存在 True # 不存在 False if not isExists: # 判斷結(jié)果 os.makedirs(path)# 如果不存在則創(chuàng)建目錄 # 創(chuàng)建目錄操作函數(shù) return True#print (path + ' 創(chuàng)建成功') else: # 如果目錄存在則不創(chuàng)建,并提示目錄已存在 #print(path + ' 目錄已存在') return False def downloadimage(imageid,imgname):##下載大圖和帶水印的高質(zhì)量大圖 url = 'https://weiliicimg9.pstatp.com/weili/l/'+str(imageid)+'.webp' url2 = 'https://icweiliimg9.pstatp.com/weili/l/'+str(imageid)+'.webp' b=False r = requests.get(url) print(r.status_code) if(r.status_code!=200): r=requests.get(url2) with open(imgname+'.jpg', 'wb') as f: f.write(r.content) print(imgname+" 下載成功") def getText(text,free): texturl = parse.quote(text) url="https://stock.tuchong.com/"+free+"search?term="+texturl+"&use=0" print(url) req=requests.get(url,headers=header) soup=BeautifulSoup(req.text,'lxml') js=soup.select('script') path='' if not free.__eq__(''): js=js[1] path='無水印/' else: js=js[4] path='圖蟲創(chuàng)意/' print(js) pattern = re.compile(r'window.hits = (\[)(.*)(\])') va = pattern.search(str(js)).group(2)#解析js內(nèi)容 print(va) va = va.replace('{', '{').replace('}', '},,') print(va) va = va.split(',,,') print(va) index = 1 for data in va: try: dict = json.loads(data) print(dict) imgname='img2/'+path+text+'/'+dict['title']+str(index) index+=1 mkdir('img2/'+path+text) imgid=dict['imageId'] downloadimage(imgid,imgname) except Exception as e: print(e) if __name__ == '__main__': num=input("高質(zhì)量大圖帶水印輸入1,普通不帶水印輸入2:") num=int(num) free='' if num==2: free='free/' text = input('輸入關(guān)鍵詞:') getText(text,free)
這樣,整個流程就完成了,在使用方面,先輸入1或2(1代表有水印高質(zhì)量圖,2代表共享圖),在輸入關(guān)鍵詞即可批量下載。
感謝各位的閱讀!看完上述內(nèi)容,你們對如何使用python批量下載圖片大概了解了嗎?希望文章內(nèi)容對大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享名稱:如何使用python批量下載圖片-創(chuàng)新互聯(lián)
網(wǎng)站URL:http://www.ef60e0e.cn/article/dgegcs.html