简单爬虫架构

整理笔记,来自imooc课程

整体结构

爬虫调度端

  • URL管理器
  • 网页下载器
  • 网页解析器

URL管理器

  • 管理待抓取的URL集合和已抓取的URL集合
  • URL管理器存在的目的:防止重复抓取,防止循环抓取
  • 应有的功能:
    • 添加新URL到待爬取集合
    • 判断新添加URL是否在容器中
    • 获取带爬取URL
    • 判断是否还有待爬取URL
    • 将爬取的URL移动到已爬取集合
  • URL管理器的实现方式
    • 将所有URL集合放入内存中(如:python set())
    • 将URL放入关系数据库中(如:MySQL urls(url, is_crawled))
    • 将URL放入缓存数据库中(如:redis)

网页下载器

  • 将互联网上URL对应的网页下载到本地的工具
  • 常见下载器(只介绍urllib2)
    • urllib2
    • requests
# -*- coding: utf-8 -*-
# python version: 2.7.9

import urllib2
import cookielib


url = "http://www.baidu.com"

# 第一种方法
response = urllib2.urlopen(url)
print(response.getcode())
print(len(response.read()))

# 第二种方法 添加header
request = urllib2.Request(url)
request.add_header('User-Agent', 'Mozilla/5.0')
response2 = urllib2.urlopen(request)
print(response.getcode())
print(cj)
print(len(response.read()))

# 第三种方法 添加对cookie的处理
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
response3 = urllib2.urlopen(url)
print(response3.getcode())
print(cj)
print(response3.read())

网页解析器

  • 从网页中提取有价值数据的工具
  • 通过网页解析器:爬取有价值的数据和新URL列表
  • 常见网页解析器:
    • regex (把文档作为字符串进行模糊匹配)
    • html.parser (结构化解析)
    • BeautifulSoup (结构化解析)
    • lxml (结构化解析)
  • BeautifulSoup
    • Documentation
from bs4 import BeautifulSoup


soup = BeautifulSoup(html_doc,              # html文档字符串
                     'html.parser',         # html解析器
                     from_encoding='utf8'   # 指定html编码
                     )

# 查找所有标签为a的节点
soup.find_all('a')

# 查找所有标签为a,连接符合/view/123.html形式的节点
soup.find_all('a', href='view/123.html')
soup.find_all('a', href=re.compile(r'/view/d+\.html'))

# 查找所有标签为div,class为abc, 文字为Python的节点
soup.find_all('div', class_='abc', string='Python')

# 得到节点:Python
# 获取查抄到的节点的标签名称
node.name

# 获取查找到的a节点的href属性
node['href']
# 获取节点的文字
node.get_text()

开发一个个百度百科简单爬虫

  • 确定目标
  • 分析目标
    • URL格式,确定抓取范围
    • 数据格式
    • 网页编码,在网页解析器指定编码
  • 编写代码
  • 执行代码

python版本 2.7.9:百科爬虫代码

你可能感兴趣的:(简单爬虫架构)