robots协议
Robots Exclusion Standard,网络爬虫排除标准
作用:
网站告知网络爬虫哪些页面可以抓取,哪些不行
形式:
在网站根目录下的robots.txt文件
*注释,代表所有,/代表根目录
User‐agent: * 爬虫来源
Disallow: / 不允许访问的内容
https://www.jd.com/robots.txt
User-agent: *
Disallow: /?*
Disallow: /pop/.html
Disallow: /pinpai/.html?*
即表示任何的网络爬虫来源都不允许爬取带有上述通配符的网页
User-agent: EtaoSpider
Disallow: /
意思是eTaospider的网络爬虫是不允许爬取任何网页的内容
User-agent: HuihuiSpider
Disallow: /
User-agent: GwdangSpider
Disallow: /
User-agent: WochachaSpider
Disallow: /
robots协议的使用
网络爬虫:
自动或人工识别robots.txt,再进行内容爬取
约束性:
Robots协议是建议但非约束性,网络爬虫可以不遵守,但存在法律风险
京东商品页面的爬取实例:
选一个京东商品,复制他的url链接,进行爬取
import requests
r=requests.get("https://item.jd.com/2967929.html")
r.status_code //可以得到200,说明访问成功
r.encodeing //输出gbk,说明从http的头部分可以解析出页面的编码信息,说明京东网站提供了页面信息的相关编码
r.text[:1000]
全代码
import requests
url="https://item.jd.com/2967929.html"
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败")
亚马逊商品的爬取
源代码
import requests
url="https://www.amazon.cn/gp/product/B01M8L5Z3Y"
try:
kv={'user-agent':'Mozilla/5.0'}
r=requests.get(url,headers=kv)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[1000:2000])
except:
print("爬取失败")
如果不添加user-agent’:'Mozilla/5.0
则访问出现了错误,
亚马逊网站对网络爬虫有限制,其中一种是通过判断对访问网站的http的头,来查看访问是否由一个爬虫引起的,网站一般接受的是浏览器引发的或者产生的http请求,对于爬虫的请求,网站可以拒绝。
- 通过r.request.headers可以查看头部信息
可知道的是该头部信息中:‘user-agent’:‘python-requests/2.11.1’
说明访问网站是由Python的requests请求引起的,因此使访问出错 - 因此可以通过改变头部信息,去模拟一个浏览器,Mozilla5.0是一个很标准的浏览器标识字段
通过以下语句即可正确的访问网页
kv={‘user-agent’:‘Mozilla/5.0’}
r=requests.get(url,headers=kv)
百度/360搜索关键词的提交
import requests
keyword="Python"
try:
kv={'wd':keyword}
r=requests.get("http://www.baidu.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
结果:
http://www.baidu.com/s?wd=Python
416928
其中Python即为搜索的关键词
360搜索全代码
import requests
keyword="Python"
try:
kv={'q':keyword}
r=requests.get("http://www.so.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
网络图片的爬取和存储
网络图片链接的格式:
http://www.example.com/picture.jpg
import requests
import os
#url="http://image.natinalgeographic.com.cn/2019/0907/20190907021719140.jpg"
url="http://image.natinalgeographic.com.cn/2017/0211/20170211061910157.jpg"
root="F://pics//"#定义的根目录
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("爬取失败")
IP地址归属地的自动查询
在网站ip138中:www.ip138.com
可以进行ip地址的查询:适合人的使用,但不适合程序