robots.txt
如果不修改头信息,requests库会把自己是爬虫的信息放到头信息里,这样可能会导致有些网站的阻拦。针对方法是修改头信息(或者应该把自己伪装成一个浏览器?)
kv = {'user-agent':'Mozilla/5.0'}
r= requests.get(url,headers=kv)
另外,检查已有的requests库头信息的代码是
r.request.headers
实例3 用python在搜索引擎模拟搜索请求
百度和360关键字接口如下
http://www.baidu.com/s?wd=keyword
http://www.so.com/s?q=keyword
返回的response对象中包含了一个request对象。这个request对象包含了比如url和上面的headers信息,代码为:
r.request.url
——另,检查字符串(?)长度的代码
len(r.text)
>>> path = 'D:/llll.jpg'
>>> url1 = 'https://i1.hoopchina.com.cn/blogfile/201703/13/BbsImg148939216583644_750x611.jpg?x-oss-process=image/resize,w_800/format,jpg'
>>> r= requests.get(url1)
>>> r.status_code
200
>>> with open(path,'wb') as f:
f.write(r.content)
52870
>>> f.close()
r.content表示以二进制的格式调用获取的数据,而图片正好就要用二进制的格式写入
import requests
import os
url1 = ''
root ='D:/'
path = path + url.split('/')[-1]
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r = requests.get(url1)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print('download img successfully!')
else:
print('the file already exists')
except:
print('false to achieve')
os库应该是用于判断文件路径的