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 爬虫--批量爬取百度图片


分享到:


相關文章: