零基础学Python-爬虫-4、下载网络图片
生活随笔
收集整理的這篇文章主要介紹了
零基础学Python-爬虫-4、下载网络图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本套課程正式進入Python爬蟲階段,具體章節(jié)根據(jù)實際發(fā)布決定,可點擊【python爬蟲】分類專欄進行倒序觀看:
【重點提示:請勿爬取有害他人或國家利益的內(nèi)容,此課程雖可爬取互聯(lián)網(wǎng)任意內(nèi)容,但無任何收益,只為大家學習分享。】
開發(fā)環(huán)境:【W(wǎng)in10】
開發(fā)工具:【Visual Studio 2019】
Python版本:【3.7】
1、創(chuàng)建項目:
2、尋找目標:直接百度搜圖片
url有共同部分,可以理解成步長為30,也就是每頁30張圖片
3、獲取圖片路徑列表:使用路徑為【https://image.baidu.com/search/acjson?tn=resultjson_com&logid=7266558810577433352&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E9%98%BF%E5%87%A1%E8%BE%BE&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word=%E9%98%BF%E5%87%A1%E8%BE%BE&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn=60&rn=30&gsm=3c&1613315170875=】自己更換即可。
由于是json數(shù)據(jù),直接解析處理即可:(寫死的路徑,)
import requestsurl ="https://image.baidu.com/search/acjson?tn=resultjson_com&logid=7266558810577433352&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E9%98%BF%E5%87%A1%E8%BE%BE&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word=%E9%98%BF%E5%87%A1%E8%BE%BE&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn=60&rn=30&gsm=3c&1613315170875=" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'} resp = requests.get(url, headers=headers) resp_json = resp.json() data_list = resp_json['data'] lst = [] for item in data_list:if len(item) != 0:lst.append(item['thumbURL']) for x in lst:print(x)4、保存圖片:
import requests import uuid import random import timeurl ="https://image.baidu.com/search/acjson?tn=resultjson_com&logid=7266558810577433352&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E9%98%BF%E5%87%A1%E8%BE%BE&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=&hd=&latest=©right=&word=%E9%98%BF%E5%87%A1%E8%BE%BE&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn=60&rn=30&gsm=3c&1613315170875=" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'} resp = requests.get(url, headers=headers) resp_json = resp.json() data_list = resp_json['data'] lst = [] for item in data_list:if len(item) != 0:lst.append(item['thumbURL'])#以下為存儲過程 # 遍歷列表存儲所有圖片 for item in lst:# 發(fā)送請求try:pic= requests.get(item, timeout=100)except requests.exceptions.ConnectionError:print ('錯誤:當前圖片無法下載')continue# uuid4為圖片名稱#,創(chuàng)建img文件夾, wb+:寫入二進制數(shù)據(jù)file=open(str.format("{0}.jpg",uuid.uuid4()), 'wb+')file.write(pic.content)file.close()#每次操作完休息1~3stimeStop=random.randint(1,4)time.sleep(timeStop) print("完成")5、總結(jié)
a)、有的時候你會發(fā)現(xiàn),可以直接處理json數(shù)據(jù),很爽的哦。
b)、但是大多時候還得一點點的拆。誒,任重道遠啊,慢慢練吧。
歡迎【點贊】、【評論】、【關(guān)注】、【收藏】、【打賞】,為推廣知識貢獻力量。
本章內(nèi)容應該是全網(wǎng)暫時下載百度圖片比較靠譜的了,如果想根據(jù)搜索詞下載圖片,直接改參數(shù)即可。
總結(jié)
以上是生活随笔為你收集整理的零基础学Python-爬虫-4、下载网络图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 零基础学Python-爬虫-3、利用CS
- 下一篇: 零基础学Python-爬虫-5、下载网络