Python开发简单爬虫--学习笔记

本文内容来自于慕课网《Python开发简单爬虫》,感兴趣的同学可以去看视频。http://www.imooc.com/learn/563

一个简单的爬虫主要分为 调度器、URL管理器、网页下载器、网页解析器几个部分,本文只涉及不需要登录操作的简单爬虫。


1.爬虫简介


爬虫是能够自动抓取互联网信息的程序

价值:新闻聚合阅读器、图书价格对比网、Python技术文章大全

2.简单爬虫架构


URL管理器主要负责存储URL,一个待爬取的URL通过下载器下载后传入解析器,再输出价值数据。



3.URL管理器

URL管理器:管理待抓取URL集合和已抓取URL集合
 ----防止重复抓取、防止循环抓取




4.网页下载器(urllib2
网页下载器是将互联网上URL对应的网页下载到本地的工具,通常使用的库有
urllib2: Python官方基础模块
requests:第三方包更强大,后期推荐使用


urllib2下载网页方法1:最简洁方法 urlopen(url)

import urllib2
#直接请求
response = urllib2.urlopen('http://www.baidu.com')

# 获取状态码,如果是200表示获取成功
print response.getcode()
#读取内容
cont = response.read()


urllib2下载网页方法2:添加data、http header

添加头文件伪装成浏览器访问是为了防止有些网站监测到爬虫封ip的情况。

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 = rullib2.urlopen("http://www.baidu.com/")

url 实例

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

print '第一种方法'
response1 = urllib2.urlopen(url)
print response1.getcode() #状态码  200表示成功
print len(response1.read())

print "第二种方法"
request = urllib2.Request(url)
request.add_header("user-agent","Mozilla/5.0")  #伪装成浏览器
response2 = urllib2.urlopen(url)
print response2.getcode()
print len(response2.read())

print '第三种方法'
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()

5.网页解析器(BeautifulSoup)

网页解析器是从网页中提取有价值数据的工具
python网页解析器种类
字符串 模糊匹配
正则表达式
结构化解析
html.parser、Beautiful Soup 、lxml

结构化解析-DOM(Document Object Model)树


通常我们使用BeautifulSoup作为网页解析器
基本语法为:

eg.

创建BeautifulSoup对象


from bs4 import BeautifulSoup

#根据HTML网页字符串创建BeautifulSoup对象
soup = BeautifulSoup(
                                     html_doc,    #HTML文档字符串
                                     'html.parser'  #HTML解析器
                                     from_encoding ='utf8'   #HTML文档的编码
                                     )

搜索节点(find_all,find)

#方法 : find_all(name,attrs,string)
#查找所有标签为a的节点
soup.find_all('a')

#查找所有标签为a,链接符合/view/123.htm形式的节点
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')


访问节点信息

#得到节点: <a href = '1.html'>Python</a>

#获取查找到的节点的标签名称
node.name

# 获取查找到的a节点的href属性
node['href']

# 获取查找到的a节点的链接文字
node.get_text()

BeautifulSoup 实例测试
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re

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 '获取lacie的链接'
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()

6.完整实例
确定目标  爬取百度百科Python词条相关的1000个页面数据
分析目标  URL格式 数据格式  网页编码
编写代码
执行爬虫

完整代码见
https://github.com/qwertypopo/baike_spider.git




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值