任意关键词采集工具,python采集百度图片到本地!

版权声明:禁止转载至其它平台,转载至博客需带上此文链接。 https://blog.csdn.net/qq_41841569/article/details/88661403

img

说明:

由于百度的网页源代码中有很多省略部分,xpath是取不到的。而且他还是一个动态的网站,数据保存在XHR中,是一个josn格式的数据。切记,新手勿操作。

学习Python中有不明白推荐加入交流群号:984632579

群里有志同道合的小伙伴,互帮互助,群里有不错的视频学习教程和PDF!

难题:

百度对python爬虫的反爬设置的相对严格,过度采集会拒绝访问,那么我们可以采用两种措施。

1、降低访问速度

2、多IP采集

自行解决。

python源代码:

# -*- coding: utf-8 -*-
# @Time : 2019/3/10 20:34
# @Author : 善念
# @File : 百度图片.py
# @Software: PyCharm
import requests
import pprint
import os
import time
name=input('请输入你要下载的图片:')
page=input('请输入你要下载的页数:')
a=0
temp=r'C:UsersDesktop'+"\"+name
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0"}
if os.path.exists(temp) ==False:
 os.mkdir(temp)
num=0
for i in range(int(page)):
 true_page = i * 48
 url = 'http://pic.sogou.com/pics?query={}&mode=1&start={}&reqType=ajax&reqFrom=result&tn=0'.format(name, true_page)
 responsed=requests.get(url,headers=headers,timeout=3)
 responsed.encoding=responsed.apparent_encoding
 response=responsed.json()
 #pprint.pprint(response)
 valus=response['items']
 print(len(valus))
 a=a+len(valus)
 for i in valus:
 print(i['pic_url'])
 pic_url=i['pic_url']
 data1=requests.get(pic_url,headers=headers,timeout=8)
 data1.close()
 data2=data1.content
 num+=1
 with open(temp+"\"+str(num)+'.jpg','wb')as f:
 f.write(data2)
print(a)
# try:
# pass
# except Exception:
# print(Exception)

猜你喜欢

转载自blog.csdn.net/qq_41841569/article/details/88661403
今日推荐