Python大作网图片采集下载,多线程图片爬虫
生活随笔
收集整理的這篇文章主要介紹了
Python大作网图片采集下载,多线程图片爬虫
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文出處:
https://cloud.tencent.com/developer/article/1666445
大作——找靈感,用大作,一個比較知名的素材類網站,里面涵蓋多行業圖片素材,類似于花瓣網,發現這種類型的素材網站還是比較多的,Python大作網圖片采集下載,多線程圖片爬蟲,多線程的方式是以前最早玩的線程池的方式實現的,但是發現好像容易出錯。
同樣的抓包分析圖片數據
發現數據還是比較多,我們耐心查找入口
對應的json數據,一目了然
大作網圖片地址還做了反爬處理,其實一般都是加一個refer地址就能搞定!
關于圖片數據,我們也可以通過瀏覽器抓包,清晰的看到
'referer': 'https://www.bigbigwork.com/tupian/image/20148309331.html',
一般添加上這個字段就能順利爬取下載圖片
運行效果:
附源碼:
#大作網采集
# -*- coding: UTF-8 -*-
import requests,time,json
from fake_useragent import UserAgent
from multiprocessing.dummy import Pool as ThreadPool
def ua():
ua=UserAgent()
headers={"User-Agent":ua.random}
return headers
def get_list():
img_urls=[]
url="https://www.bigbigwork.com/q?w=texture%20patterns&c=%E7%BA%B9%E7%90%86&h=%E5%B7%A5%E4%B8%9A%E8%AE%BE%E8%AE%A1"
response=requests.get(url,headers=ua(),timeout=6).content.decode('utf-8')
time.sleep(1)
response_dict=json.loads(response)
print(len(response_dict['data']))
datas=response_dict['data']
for data in datas:
img_urls.append(data['bUrl'])
return img_urls
#單線程
def tps(img_urls):
ua = UserAgent()
headers = {
'referer': 'https://www.bigbigwork.com/tupian/image/20148309331.html',
'User-Agent': ua.random,
}
i=1
for img_url in img_urls:
r = requests.get(img_url,headers=headers,timeout=6)
time.sleep(1)
with open(f'{i}.jpg','wb')as f:
f.write(r.content)
print("下載圖片成功")
i=i+1
#多線程調用版本
def tp(img_url):
ua = UserAgent()
headers = {
'referer': 'https://www.bigbigwork.com/tupian/image/20148309331.html',
'User-Agent': ua.random,
}
img_name=img_url.split('/')[-1]
r = requests.get(img_url,headers=headers,timeout=6)
time.sleep(1)
with open(img_name,'wb')as f:
f.write(r.content)
print(f"{img_name}下載圖片成功")
def run():
img_urls=get_list()
try:
# 開4個 worker,沒有參數時默認是 cpu 的核心數
pool = ThreadPool()
results = pool.map(tp, img_urls)
pool.close()
pool.join()
print("采集所有圖片完成!")
except:
print("Error: unable to start thread")
if __name__=='__main__':
run()
總結
以上是生活随笔為你收集整理的Python大作网图片采集下载,多线程图片爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 删除特定Dns后缀_DNS根服务器里存了
- 下一篇: aws s3仅允许cloudfront访