爬虫分类
通用爬虫
常用就是 搜索引擎, 无差别的收集数据,存储,提取关键字,构建索引(倒排索引)库,给用户提供搜索接口
爬取一般流程:
- 初始化一批URL,将这些url放到待爬取队列。
- 从队列取出这些url,通过DNS解析IP, 对IP对应的站点下载HTML页面,保存到本地服务中,url放到已爬取队列。
- 分析这些网页内容,找出网页里面的其他关心的url链接,继续执行第二步,直到爬取结束。
搜索引擎如何获取一个新网站的URL
- 新网站主动提交给搜索引擎
- 通过其他网站页面中设置外链
- 搜索引擎和DNS服务商合作,获取最新收录的网站
聚焦爬虫
有针对性的编写特定领域数据的爬取程序,是面向主题的爬虫
爬取流程与通用爬虫一样
Robots协议 (爬虫遵守的协议)
指定一个robots.txt文件,告诉爬虫引擎什么可以爬取
淘宝 http://www.taobao.com/robots.txt
User-agent: Baiduspider // 来源
Allow: /article // 允许爬的内容
Disallow: /product/ // 不允许爬的内容
Http请求金额响应处理
其实爬取网页就是通过HTTP协议访问网页,不过通过浏览器访问往往是人的行为,把这种行为变成使用程序来访问
urllib包
urllib是标准库,它一个工具包模块,包含下面模块来处理url:
- urllib.request 用于打开和读写url
- urllib.error 包含了由urllib.request引起的异常
- urllib.parse用于解析url
- urllib.robotparser分析robots.txt文件
爬虫伪装
有些网站是反爬虫的,所以要把爬虫伪装成浏览器。随便打开是一个浏览器,复制浏览器的user-agent值,用来伪装加载header中
from urllib.request import urlopen,Request
import ssl
url = 'http://www.bing.com'
ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' # chrome的user-agent
request = Request(url); #返回一个Request类实例
request.add_header('User-Agent', ua) #伪装
context = ssl._create_unverified_context() #忽略不信任证书检查,解决https网站ssl证书问题
#打开页面
response = urlopen(request, context=context) # get方法
response = urlopen(request, data={},context=context) # 加data是POST方式
with response:
print(response.geturl()) # 得到真正的url
print(response.info()) # 得到headers信息
print(response.read()) # 读取返回内容
print(response.get_header('User-agent')) # 获取头部ua信息
url参数的编码和解码
from urllib import parse
u = parse.urlencode({'wd': '中'}) # 编码 ('wd=%E9' 16进制码)
url = 'http://www.baidu.com/s?{}'.format(u)
print(parse.unquote(u)) #解码
根据Xpath语法进行条件过滤
from lxml import etree # etree是构建html,lxml是XML和html的解析库
#anode = etree.Html(text) 解析HTML文档,返回根结点
#anode.xpath("//div[@class='one'].text()") 返回根结点的文本内容
from urllib.request import urlopen,Request
import ssl
url = 'http://www.bing.com'
ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36' # chrome的user-agent
request = Request(url); #返回一个Request类实例
request.add_header('User-Agent', ua) #伪装
context = ssl._create_unverified_context() #忽略不信任证书检查,解决https网站ssl证书问题
#打开页面
response = urlopen(request, context=context) # get方法
with response:
html = etree.Html(response)
html.xpath('//div[@class='one']//text()') #得到所有class为one下所有的内容,返回值是一个可迭代对象