网络爬虫的盗亦有道
网络爬虫的尺寸
爬取网页,玩转网页:小规模,数据量小,爬取速度不敏感;Requests库
爬取网站 爬取系列网站:中规模,数据量较大,爬取速度敏感;Scrapy库
爬取全网:大规模,搜索引擎,爬取速度关键;定制开发
网络爬虫引发的问题
网络爬虫的骚扰:受限于编写水平和目的,网络爬虫将会为Web服务器带来巨大的资源开销
网络爬虫的法律风险:服务器上的数据有产权归属,网络爬虫获取数据后牟利将带来法律风险
网络爬虫泄露隐私:网络爬虫可能具备突破简单访问控制的能力,获得被保护数据从而泄露个人隐私
网络爬虫的限制
来源审查:判断UserAgent进行限制
检查来访HTTP协议头的UserAgent域,只响应浏览器或友好爬虫的访问
发布公告:Robots协议告知所有爬虫网站的爬取策略,要求爬虫遵守Robots协议
Robots Exclusion Standard 网络爬虫排除标准作用:网站告知网络爬虫哪些页面可以抓取,哪些不行
形式:在网站根目录下的robots.txt文件
Robots协议基本语法:
https://www.jd.com/robots.txt
User-agent: * # 注释:
Disallow: /?* *代表所有
Disallow: /pop/*.html /代表根目录
Robots协议的遵守方式
网络爬虫使用Robots协议:自动或人工识别robots.txt,再进行内容爬取
约束性:Robots协议是建议但非约束性,网络爬虫可以不遵守,但存在法律风险
Requests库爬取实例
实例1:京东商品页面的爬取
import requests
url = "https://item.jd.com/100004770249.html"
try:
kv = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'}
r = requests.get(url,headers=kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败" )
例2:亚马逊商品页面的爬取
import requests
url = "https://www.amazon.cn/dp/B01MYH8A99"
try:
kv = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'}
r = requests.get(url,headers=kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败" )
实例3:百度360搜索关键词提交
百度的关键词接口: http://www.baidu.com/s?wd=keyword
360的关键词接口: http://www.so.com/s?q=keyword
import requests
url = "https://www.baidu.com/s"
try:
kv = {'wd':"python"}
#kv = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'}
r = requests.get(url,params=kv)
r.raise_for_status()
print(r.request.url)
print(len(r.text))
except:
print("爬取失败" )
实例4:网络图片的爬取和存储
网络图片链接的格式:http://www.example.com/picture.jpg
图片爬取代码
import requests
import os
url = 'https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4wwtv?ver=1428'
path = "E://pystudy//1.jpg"
if not os.path.exists(path):
kv = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'}
r = requests.get(url, headers=kv)
r.raise_for_status()
with open(path, 'wb') as f:
f.write(r.content) # r.content表示返回内容的二进制形式,
f.close() # 图片是以二进制形式存储的
print("文件保存成功")
else:
print("文件已存在")
########
import requests
url = 'https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4wwtv?ver=1428'
r = requests.get(url)
with open('E://pystudy//2.jpg', 'wb') as f:
f.write(r.content)
实例5:IP地址归属地的自动查询
ip138 IP查询:http://m.ip138.com/ip.asp?ip=ipaddress
import requests
url = "http://m.ip138.com/ip.asp?ip="
r = requests.get(url + '202.204.80.112')
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[:1000])