《2018年5月23日》【连续225天】
标题:Robots协议,一些实例;
内容:
对于网络爬虫,一般网站有两种法案来限制:
1.来源审查:检查访问者的User-Agent,只允许浏览器和友好爬虫访问;
2.Robots协议,告诉爬虫哪些内容可以爬取,哪些不可以;
#注释, *代表所有。 /根目录
爬取实例:
以京东某页面为例:
import requests
url ="https://item.jd.hk/1986180918.html"
try:
r = requests.get(url)
r.raise_for_status()
r.encoding= r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败")
实例2:
当我们以以上手段爬取亚马逊的某个页面时,会出现503的信息,
这是因为亚马逊采用了来源审查,所以我们要更改user-agent
kv ={'user-agent':'Mozilla/5.0'}
r =requests.get(url,headers = kv)
实例3:搜索关键词提交:
import requests
keyword ="Python"
url ="https://baidu.com/s"
try:
kv ={'wd':keyword}
r = requests.get(url,params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
实例4:照片爬取:
import requests
import os
root ="D://PYECourse//"
url ="https://img13.360buyimg.com\
/n5/s75x75_jfs/t22156/151/4151843/262922/77982b73/5af4f4ddN52f986f2.jpg"
path =root+url.split('/')[-1]
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r =requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已存在")
except:
print("爬取失败")