开发简单爬虫
来源:互联网 发布:浙江软件考试网 编辑:程序博客网 时间:2024/05/21 02:52
开发简单爬虫
调度器 –> 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()
- Python开发简单爬虫
- Qt 简单爬虫开发
- python开发简单爬虫
- Python开发简单爬虫
- Python开发简单爬虫
- python 开发简单爬虫
- 开发简单爬虫
- python开发简单爬虫笔记
- 一个简单的爬虫开发
- 2---python开发简单爬虫
- Python开发简单爬虫之爬虫介绍(一)
- Python开发简单爬虫(二)
- Python开发简单爬虫(一)
- Python开发简单爬虫(笔记)
- Python 开发简单爬虫 学习笔记1
- python开发简单爬虫:准备篇
- python开发简单爬虫:实战篇
- Python开发简单爬虫--学习笔记
- 线性代数 01.04 克拉默法则
- 共享内存函数(shmget、shmat、shmdt、shmctl)及其范例
- Ubuntu如何使用GitHub(二)
- 决策树之ID3算法
- Java高级编程都有哪些知识点
- 开发简单爬虫
- AndroidStudio手机本地音乐的读取
- 四分树--uva297
- java中的序列化
- bzoj2502 清理雪道(有源汇有上下界最小流)
- 第十三届北航程序设计竞赛预赛题解
- Ubuntu报错'_NamespacePath' object has no attribute 'sort'
- CentOS6.5 32位Out of Memery问题分析
- Slim 框架学习,第十五天 _Router(六)