Python网络爬虫与信息提取
1.网络爬虫引发的问题
网络爬虫的尺寸 | 描述 | 支持库 | 占比 |
---|---|---|---|
小规模,数据量小,爬取速度不敏感 | 爬取网页 玩转网页 | Requests库 | >90% |
中规模,数据规模较大,爬取速度敏感 | 爬取网站 爬取系列网站 | Scrapy库 | |
大规模,搜索引擎,爬取速度敏感 | 爬取全网 | 定制开发 |
网络爬虫的“骚扰”
- 受限于编写水平和目的,网络爬虫将会为web服务器带来巨大的资源开销。
网络爬虫的法律风险
- 服务器上的数据有产权归属
- 网络爬虫获取数据后牟利将带来法律风险
网络爬虫泄露隐私
- 网络爬虫可能具备突破简单访问控制的能力,获得被保护数据从而泄露个人隐私。
2.网络爬虫的限制
来源审查:判断User-Agent进行限制
- 检查来访HTTP协议头的User-Agent域,只响应浏览器或友好爬虫的访问。
发布公告:Robots协议
- 告知所有爬虫网址的爬取策略,要求爬虫遵守。
3.Robots协议
Robots Exclusion Protocol 网络爬虫排除标准
作用:网站告知网络爬虫哪些网页可以抓取,哪些不行。
形式:在网站根目录下的robots.txt文件
Robots协议基本语法
# 注释,*代表所有,/代表根目录
User-agent:*
Disallow:/
4.Robots协议的遵守方式
Robots协议的使用
网络爬虫:自动或人工识别robots.txt,再进行内容爬取。
约束性:Robots协议是建议但非约束性,网络爬虫可以不遵守,但存在法律风险,
对Robots协议的理解
类型 | 访问特征 | 是否遵守 |
---|---|---|
爬取网页 玩转网页 | 访问量很小 | 可以遵守 |
爬取网页 玩转网页 | 访问量较大 | 建议遵守 |
爬取网站 爬取系列网站 | 非商业且偶尔 | 建议遵守 |
爬取网站 爬取系列网站 | 商业利益 | 必须遵守 |
爬取全网 | 必须遵守 |
如果爬虫类人行为爬取数据可不参考robots协议
5.网络爬虫的几个实例
实例:1.京东商品页面爬取
import requests
url = "https://item.jd.com/100008348542.html"
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
requests
print(r.text[:1000])#只显示前1000个字符
except requests.HTTPError:
print("爬取失败")
实例:2.亚马逊商品页面爬取(添加浏览器标识,好像已不适用)
import requests
url = "https://www.amazon.cn/dp/B07K14XKZH"
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)
except requests.HTTPError:
print("爬取失败")
实例:3.百度/360搜索关键词提交
百度的关键词接口:
http://www.baidu.com/s?wd=keyword
import requests
url = "http://www.baidu.com/s"
try:
kv = {'wd': 'python'}
r = requests.get(url, params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except requests.HTTPError:
print("爬取失败")
360的关键词接口:
http://www.so.com/s?q=keyword
import requests
url = "http://www.so.com/s"
try:
kv = {'q': 'python'}
r = requests.get(url, params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except requests.HTTPError:
print("爬取失败")
实例:4.网络图片的爬取和存储
网络图片链接格式:
http://www.example.com/picture.jpg
import requests
import os
root = "F:/pc/"
url = "https://www.python.org/static/img/python-logo.png"
path = root + url.split("/")[-1]# 图面的原文件名
try:
if not os.path.exists(root):#判断目录是否存在
os.makedirs(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 requests.HTTPError:
print("爬取失败")
实例:5.IP地址归属地的自动查询
ip138网页提供IP地址归属地查询
查询接口为
http://ip138.com/ips138.asp?ip=ipaddress
import requests
url = "http://ip138.com/ips138.asp?ip="
try:
r = requests.get(url + "202.204.80.112")
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[-3000:-2000])
except requests.HTTPError:
print("爬取失败")