Python 爬蟲--批量爬取百度圖片


1 首先要配置環境,這裡使用到的是requests第三方庫


<code>pip install requests/<code>

2.requests使用:

簡單介紹一下requests的常用方法,基本知道一個requests.get()和requests.post()就行了。requests的返回值可以有多種形式輸出,最常用的是".text"和".content",前者輸出unicode,後者輸出二進制。其他方法忘了可以查手冊:requests快速上手

3.python正則模塊使用:

python的正則模塊是re,這裡主要用到的函數是:

findall(pattern,str,re.S)

(re.S的意思是讓"."可以匹配換行符,不然有些標籤頭和尾是分幾行的,就會匹配失敗)

正則表達式用到的是:

(.*?)

( ):表示這個內容是我們需要提取的

.*:表示匹配任意字符0-n次

?:表示非貪心,找到第一個就停下來

下面是完整代碼:

<code>#!/usr/bin/env python 

# -*- coding: utf-8 -*-
import requests
import os

def getManyPages(keyword,pages):
params=[]
for i in range(30,30*pages+30,30):
params.append({
'tn': 'resultjson_com',
'ipn': 'rj',
'ct': 201326592,
'is': '',
'fp': 'result',
'queryWord': keyword,
'cl': 2,
'lm': -1,
'ie': 'utf-8',
'oe': 'utf-8',
'adpicid': '',
'st': -1,
'z': '',
'ic': 0,
'word': keyword,
's': '',
'se': '',
'tab': '',
'width': '',
'height': '',
'face': 0,
'istype': 2,
'qc': '',
'nc': 1,
'fr': '',
'pn': i,
'rn': 30,
'gsm': '1e',
'1488942260214': ''
})
url = 'https://image.baidu.com/search/acjson'
urls = []
for i in params:
urls.append(requests.get(url,params=i).json().get('data'))

return urls


def getImg(dataList, localPath):

if not os.path.exists(localPath): # 如果給定的路徑不存在文件夾,新建文件夾

os.mkdir(localPath)

x = 0
for list in dataList:
for i in list:
\t\t\t#thumbURL,middleURL,hoverURL 三種圖片資源路徑可選,根據需求選擇
if i.get('thumbURL') != None:
print('正在下載:%s' % i.get('thumbURL'))
ir = requests.get(i.get('thumbURL'))
open(localPath + '%d.jpg' % x, 'wb').write(ir.content)
x += 1
else:
print('圖片鏈接不存在')

if __name__ == '__main__':
word = input("請輸入關鍵詞: ")
j = input("請輸入頁數: ")
dataList = getManyPages(word,(int (j))) # 參數1:關鍵字,參數2:要下載的頁數
getImg(dataList,'pictures2/') # 參數2:指定保存的路徑/<code>

把代碼保存成download_img.py

在控制檯支持


Python 爬蟲--批量爬取百度圖片

這是下載下來的圖片,根據圖片的需求,可以下載縮略圖,或者高清圖片,修改參數

thumbURL,middleURL,hoverURL,三種圖片資源路徑可選,根據需求選擇

Python 爬蟲--批量爬取百度圖片


分享到:


相關文章: