python简单爬虫实现day1
一、简单爬虫架构
- 爬虫调度端
- URL管理器
- 网页下载器
- 网页解析器
- 价值数据
二、模块分析
1.URL管理器
URL管理器:管理待抓取URL集合和已抓取URL集合
- 防止重复抓取、防止循环抓取
功能:
实现方式:
- 内存 (python内存,待爬取URL集合:set(),已爬取URL集合:set())*个人、小公司
- 关系数据库(mysql, url(url, is_crawled))*内存不够用、永久存储数据
- 缓存数据库(redis,带爬取URL集合:set(),已爬取URL集合:set())*大公司
2.网页下载器
网页下载器:将互联网上URL对应的网页下载到本地的工具。
python有哪几种网页下载器:
- urllib2 —— python官方基础模块
- requests —— 第三方包更强大
urllib2 下载网页方法1:最简洁的方法
import urllib2 #直接请求 response = urllib2.urlopen('http://www.baidu.com') # 获取状态码,如果是200表示获取成功 print response.getcode() #读取内容 cont = response.read()
urllib2 下载网页方法2:添加data、http header
import urllib2 # 创建Request对象 request = urllib2.Request(url) #添加数据 request.add_data('a', '1') #添加http的header request.add_header('User-Agent', 'Mozilla/5,0') #发送请求获取结果 response = urllib2.urlopen(request)
urllib2 下载网页方法3:添加特殊情景的处理器
import urllib2, cookielib #创建cookie容器 cj = cookielib.CookieJar() #创建1个opener opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) #给urllib2安装opener urllib2.install_opener(opener) #使用带有cookie的urllib2访问网页 response = urllib2.urlopen("http://www.baidu.com/")
3.网页解析器
网页解析器:从网页中提取有价值数据的工具
HTML网页字符串-->网页解析器-->价值数据& 新URL列表
python有哪几种网页解析器:
- 正则表达式 - - 模糊匹配
- html.parser
- Beautiful Soup * - - 结构化解析
- lxml
什么是网页解析器?
结构化解析-DOM (Document Object Model)
Beautiful Soup
安装并测试beautifulsoup4
- 安装:pip install beautifulsoup4
- 测试:import bs4
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')
print('所有的链接') links = soup.find_all('a') for link in links: print(link.name, link['href'], link.get_text())
print('获取locie的链接') link_node = soup.find('a', href='http://example.com/lacie') print(link_node.name, link_node['href'], link_node.get_text())
print('正则匹配') link_node = soup.find('a', href=re.compile(r"ill")) print(link_node.name, link_node['href'], link_node.get_text())
print('获取p段落文字') p_node = soup.find('p', class_='title') print(p_node.name, p_node.get_text())