python+正则+多进程爬取糗事百科图片
生活随笔
收集整理的這篇文章主要介紹了
python+正则+多进程爬取糗事百科图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
話不多說,直接上代碼;
# 需要的庫 import requests import re import os from multiprocessing import Pool # 請求頭 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' }# 主函數 def get_img(url):# 定義圖片存儲路徑img_path = './img/'if not os.path.exists(img_path):os.mkdir(img_path)try:# 請求網頁response = requests.get(url=url,headers=headers)# 正則提取圖片地址response = re.findall('<div class="thumb".*?<img src="(.*?)".*?</a>',response.text,re.S)# 循環圖片地址for i in response:# 拼接完整圖片路由url = ('http:' + i)# 請求完整圖片路由response = requests.get(url,headers)# 圖片命名img_name = url.split('/')[-1]# 判斷圖片是否已下載if os.path.exists(img_path+img_name):print('圖片已存在')else:# 下載圖片with open(img_path+img_name,'wb') as f:f.write(response.content)print('正在下載:'+url)except Exception as e:print(e) # 程序主入口 if __name__ == '__main__':# 構造所有ip地址urls = ['https://www.qiushibaike.com/imgrank/page/{}/'.format(i) for i in range(1,14)]# 使用多進程pool = Pool()# 開啟多進程爬取pool.map(get_img,urls)print('下載完畢')下載中;
打開文件夾查看圖片;
總結
以上是生活随笔為你收集整理的python+正则+多进程爬取糗事百科图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django项目简单调取百度翻译接口
- 下一篇: python爬虫中的ip代理设置