开发简单爬虫
调度器 –> URL管理器 –> 下载器 –> 解析器 –> 应用
URL管理器:
管理带抓取URL集合和已抓取URL集合
实现方式:内存,关系数据库,缓存数据库
使用内存进行存储,使用set()集合
网页下载器:
将互联网上URL对应的网页下载到本地的工具
网页下载器有:urllib2(官方基础模块) requests(第三方插件)
- 实现方法1:
import urllib2(3.6:urllib.request)
直接请求
response = urllib2.urlopen('http://www.baidu.com')
获取状态码,如果是200表示获取成功
print(response.getcode())
读取内容
cont = response.read()
- 实现方法2:
import urllib2(3.6:urllib.request)
创建Request对象
request = urllib2.Request(url)
添加数据
request.add_data('a', '1')
添加http的header
request.add_header('User-Agent', 'Mozilla/5.0')
发送请求获取结果
response = urllib2.urlopen(request)
- 实现方法3:
import urllib2, cookielib(3.6:urllib.request http.cookilejar)
创建cookie容器
cj = cookielib.CookieJar()
创建一个opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
给urllib2安装opener
urllib2.install_opener(opener)
使用带有cookie的urllib2访问网页
response = urllib2.urlopen('http://www.baidu.com')
网页解析器:
从网页中提取有价值的数据
正则表达式 / html.parser / Beautiful Soup / lxml
BeautifulSoup 语法:
1.创建BeautifulSoup对象:
from bs4 import BeautifulSoup
根据HTML网页字符串创建BeautiSoup对象
soup = BeautifulSoup( html_doc, # HTML文档字符串 'html.parser', # HTML解析器 from_encoding='utf8', # HTML文档的编码 );
2.搜索节点(find_all, find)
方法:find_all(name, attrs, string)
查找所有标签为a的节点
soup.find_all('a')
查找所有标签为a,链接符合/view/123.html形式的节点
soup.find_all('a', href='/view/123.htm')
soup.find_all('a', href=re.compile(r'/view/\d+\.htm))
查找所有标签为div,class为abc, 文字为Python的节点
soup.find_all('div', class_='abc', string='Python')
3.访问节点信息
得到节点:
<a href='1.html'>Python</a>
获取查找到的节点的标签名称
node.name
获取查找到的a节点的href属性
node['href']
获取查找到的a节点的链接文字
node.get_text()