类似的文章应该会有很多,提供一下自己的理解,希望能够帮到想要学习python的人,仅供学习使用!!
import requests
from urllib.request import quote, urlretrieve
import time
class Spider():
def __init__(self, url, keyword,page):
self.keyword=keyword
self.url = url.format(quote(keyword))
self.urls=[]
for i in range(1,page):
self.go(page)
def go(self,page):
#headers需要设置,不然无法获得请求,应该是做了一定的反爬处理
headers = {
'user-agent': 'Mozilla / 5.0(Windows NT 6.1;WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 85.0.4183.121Safari / 537.36',
}
#里面有些参数没什么用,可以取消,复制自己浏览器的参数即可
params = {
'tn': 'resultjson_com',
'logid': '8821183599160709086',
'ipn': 'rj',
'ct': '201326592',
'is': '',
'fp': 'result',
'queryWord': '风景',
'cl': '2',
'lm': '-1',
'ie': 'utf-8',
'oe': 'utf-8',
'adpicid': '',
'st': '-1',
'z': '',
'ic': '0',
'hd': '',
'latest': '',
'copyright': '',
'word': self.keyword,
's': '',
'se': '',
'tab': '',
'width': '',
'height': '',
'face': '0',
'istype': '2',
'qc': '',
'nc': '1',
'fr': '',
'expermode': '',
'force': '',
'pn': '60',
'rn': '{}'.format(page*30),
'gsm': '3c',
str(int(time.time())): '',
}
res = requests.get(self.url, headers=headers, params=params).json()['data']
for u in res:
try:
fl=u['replaceUrl'][1]['ObjUrl']
self.urls.append(fl)
urlretrieve(fl,'./pics/'+fl.split('/')[-1])#下载路径徐更改,使用urlretrieve下载挺方便的
time.sleep(1)
except:
pass
if __name__ == '__main__':
url = 'https://image.baidu.com/search/acjson?'
keyword = '风景'
spider = Spider(url, keyword,2)
#通过获取json文件的方式会出现有的图片无法下载