Python 爬取網(wǎng)頁圖片詳解流程
簡介
快樂在滿足中求,煩惱多從欲中來
記錄程序的點點滴滴。
輸入一個網(wǎng)址從這個網(wǎng)址中解析出圖片,并將它保存在本地
流程圖

程序分析
解析主網(wǎng)址
def get_urls():
url = 'http://www.nipic.com/show/35350678.html' # 主網(wǎng)址
pattern = "(http.*?jpg)"
header = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}
r = requests.get(url,headers=header)
r.encoding = r.apparent_encoding
html = r.text
urls = re.findall(pattern,html)
return urls
url 為需要爬的主網(wǎng)址pattern 為正則匹配header 設(shè)置請求頭r = requests.get(url,headers=header) 發(fā)送請求r.encoding = r.apparent_encoding 設(shè)置編碼格式,防止出現(xiàn)亂碼
| 屬性 | 說明 |
|---|---|
| r.encoding | 從http header中提取響應(yīng)內(nèi)容編碼 |
| r.apparent_encoding | 從內(nèi)容中分析出的響應(yīng)內(nèi)容編碼 |
urls = re.findall(pattern,html) 進行正則匹配
re.findall(pattern, string, flags=0)
正則 re.findall 的簡單用法(返回string中所有與pattern相匹配的全部字串,返回形式為數(shù)組)
下載圖片并存儲
def download(url_queue: queue.Queue()):
while True:
url = url_queue.get()
root_path = 'F:\\1\\' # 圖片存放的文件夾位置
file_path = root_path + url.split('/')[-1] #圖片存放的具體位置
try:
if not os.path.exists(root_path): # 判斷文件夾是是否存在,不存在則創(chuàng)建一個
os.makedirs(root_path)
if not os.path.exists(file_path): # 判斷文件是否已存在
r = requests.get(url)
with open(file_path,'wb') as f:
f.write(r.content)
f.close()
print('圖片保存成功')
else:
print('圖片已經(jīng)存在')
except Exception as e:
print(e)
print('線程名: ', threading.current_thread().name,"url_queue.size=", url_queue.qsize())
此函數(shù)需要傳一個參數(shù)為隊列
queue模塊中提供了同步的、線程安全的隊列類,queue.Queue()為一種先入先出的數(shù)據(jù)類型,隊列實現(xiàn)了鎖原語,能夠在多線程中直接使用。可以使用隊列來實現(xiàn)線程間的同步。url_queue: queue.Queue() 這是一個隊列類型的數(shù)據(jù),是用來存儲圖片URLurl = url_queue.get() 從隊列中取出一個urlurl_queue.qsize() 返回隊形內(nèi)元素個數(shù)
全部代碼
import requests
import re
import os
import threading
import queue
def get_urls():
url = 'http://www.nipic.com/show/35350678.html' # 主網(wǎng)址
pattern = "(http.*?jpg)"
header = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}
r = requests.get(url,headers=header)
r.encoding = r.apparent_encoding
html = r.text
urls = re.findall(pattern,html)
return urls
def download(url_queue: queue.Queue()):
while True:
url = url_queue.get()
root_path = 'F:\\1\\' # 圖片存放的文件夾位置
file_path = root_path + url.split('/')[-1] #圖片存放的具體位置
try:
if not os.path.exists(root_path):
os.makedirs(root_path)
if not os.path.exists(file_path):
r = requests.get(url)
with open(file_path,'wb') as f:
f.write(r.content)
f.close()
print('圖片保存成功')
else:
print('圖片已經(jīng)存在')
except Exception as e:
print(e)
print('線程名:', threading.current_thread().name,"圖片剩余:", url_queue.qsize())
if __name__ == "__main__":
url_queue = queue.Queue()
urls = tuple(get_urls())
for i in urls:
url_queue.put(i)
t1 = threading.Thread(target=download,args=(url_queue,),name="craw{}".format('1'))
t2 = threading.Thread(target=download,args=(url_queue,),name="craw{}".format('2'))
t1.start()
t2.start()
到此這篇關(guān)于Python 爬取網(wǎng)頁圖片詳解流程的文章就介紹到這了,更多相關(guān)Python 爬取網(wǎng)頁圖片內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信