python爬虫入门笔记(上)



一.爬虫是什么?

爬虫:一段自动抓取互联网信息的程序。
价值:互联网数据,为我所用。如:新闻阅读器,爆笑故事APP,Python技术文章大全。
二.简单爬虫架构:

1.爬虫调度端:启动爬虫,运行爬虫,监视爬虫的运行情况

如图:

python爬虫入门笔记(上)


python爬虫入门笔记(上)

三.url管理器:管理待抓取URL集合和已抓取URL集合
作用:防止重复抓取,循环抓取 

实现方式:目前有三种实现方式

1.内存(个人/小型使用) 2.关系数据库(永久存储) 3.缓存数据库(高性能)

如图

python爬虫入门笔记(上)


python爬虫入门笔记(上)

四.网页下载器

Python有哪几种网页下载器

1.urllib2(Python官方基础模块)

2.requests(第三方包更强大)

五.urllib2下载器

1.最简洁方法

import urllib2

# 直接请求

response=urllib2.urlopen('http://www.baidu.com')

# 获取状态码,如果200表示获取成功

print response.getcode()

# 读取内容

cont=response.read()


 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=urlib2.urlopen(request)

# 3.添加特殊情景的处理器

python爬虫入门笔记(上)

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/")