简单爬虫框架:
  爬虫调度器 -> URL管理器 -> 网页下载器(urllib2) -> 网页解析器(BeautifulSoup) -> 价值数据

Demo1:

# coding:utf8
import urllib2,cookielib url = "https://www.baidu.com" print '第一种方法'
response1 = urllib2.urlopen(url)
print response1.getcode() #返回状态码
print len(response1.read()) #返回的网页内容的长度 print "第二种方法"
request = urllib2.Request(url)
request.add_header("user-agent","Mozilla/5.0")
response2 = urllib2.urlopen(request)
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 #返回cookie
print response3.read() #返回网页内容

Python有哪几种网页解析器:
正则表达式、html.parser、Beautiful Soup、lxml

BeautifulSoup:
  - Python第三方库,用于从HTML或XML中提取数据
  - 官网:http://www.crummy.com/software/BeautifulSoup/bs4/doc/

安装并测试beautifulsoup4:
  - 安装:pip install beautifulsoup4
  - 测试:import bs4

如果PyCharm无法识别beautifulsoup4,则在设置里找到Python Intercepter这一项,改为python2.7版本即可。

Demo2:

# coding:utf-8
import re
from bs4 import BeautifulSoup # 示例代码片段(来自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 '获取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()

实战编写爬取百度百科页面:

目录结构:

注:mac osx下用alt+enter添加相应方法

(爬虫调度器)spider_main.py:

# coding=utf-8
from baike_spider import url_manager,html_downloader,html_parser,html_outputer class SpiderMain(object):
def __init__(self):
self.urls = url_manager.UrlManager() #url管理器
self.downloader = html_downloader.HtmlDownloader() #下载器
self.parser = html_parser.HtmlParser() #解析器
self.outputer = html_outputer.HtmlOutputer() #输出器 def craw(self, root_url):
count = 1 #判断当前爬取的是第几个url
self.urls.add_new_url(root_url)
while self.urls.has_new_url(): #循环,爬取所有相关页面,判断异常情况
try:
new_url = self.urls.get_new_url() #取得url
print 'craw %d : %s' % (count, new_url) #打印当前是第几个url
html_cont = self.downloader.download(new_url) #下载页面数据
new_urls, new_data = self.parser.parse(new_url,html_cont) #进行页面解析得到新的url以及数据 self.urls.add_new_urls(new_urls) #添加新的url
self.outputer.collect_data(new_data) #收集数据 if count == 10: # 此处10可以改为100甚至更多,代表循环次数
break count = count + 1
except:
print 'craw failed' self.outputer.output_html() #利用outputer输出收集好的数据 if __name__=="__main__":
root_url = "http://baike.baidu.com/view/21087.htm"
obj_spider = SpiderMain() # 创建
obj_spider.craw(root_url) # craw方法启动爬虫

(url管理器)url_manager.py:

# coding=utf-8
class UrlManager(object): def __init__(self):
self.new_urls = set() # 待爬取url
self.old_urls = set() # 已爬取url def add_new_url(self, url): # 向管理器中添加一个新的url
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
self.new_urls.add(url) def add_new_urls(self, urls): # 向管理器中添加新的更多的url
if urls is None or len(urls) == 0:
return
for url in urls:
self.add_new_url(url) def has_new_url(self): # 判断管理器是否有新的待爬取的url
return len(self.new_urls) != 0 def get_new_url(self): # 从管理器中获取一个新的待爬取的url
new_url = self.new_urls.pop()
self.old_urls.add(new_url)
return new_url

(下载器)html_downloader.py:

import urllib2

class HtmlDownloader(object):

    def download(self, url):
if url is None:
return None response = urllib2.urlopen(url) if response.getcode() != 200:
return None return response.read()

(解析器)html_parser.py:

import re
import urlparse
from bs4 import BeautifulSoup class HtmlParser(object): def parse(self,page_url,html_cont):
if page_url is None or html_cont is None:
return soup = BeautifulSoup(html_cont,'html.parser', from_encoding='utf-8')
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
return new_urls, new_data def _get_new_urls(self, page_url, soup):
new_urls = set()
# /view/123.htm
links = soup.find_all('a', href=re.compile(r"/view/\d+\.htm"))
for link in links:
new_url = link['href']
new_full_url = urlparse.urljoin(page_url, new_url)
new_urls.add(new_full_url)
return new_urls def _get_new_data(self, page_url, soup):
res_data = {}
# url
res_data['url'] = page_url # <dd class="lemmaWgt-lemmaTitle-title"> <h1>Python</h1>
title_node = soup.find('dd',class_="lemmaWgt-lemmaTitle-title").find("h1")
res_data['title'] = title_node.get_text() # <div class="lemma-summary" label-module="lemmaSummary">
summary_node = soup.find('div',class_="lemma-summary")
res_data['summary'] = summary_node.get_text() return res_data

(数据输出)html_outputer.py:

# coding=utf-8
class HtmlOutputer(object):
#初始化
def __init__(self):
self.datas = [] def collect_data(self, data): #收集数据
if data is None:
return
self.datas.append(data) def output_html(self): #输出数据
fout = open('output.html', 'w') fout.write("<html>") fout.write("<head>")
fout.write("<meta charset= 'UTF-8'>")
fout.write("</head>") fout.write("<body>")
fout.write("<table>") # ASCII
for data in self.datas:
fout.write("<tr>")
fout.write("<td>%s</td>" % data['url'])
fout.write("<td>%s</td>" % data['title'].encode('utf-8'))
fout.write("<td>%s</td>" % data['summary'].encode('utf-8'))
fout.write("</tr>") fout.write("</html>")
fout.write("</body>")
fout.write("</table>") fout.close()

运行程序spider_main.py可进行爬取页面,最终文件输出为output.html,里面包含词条和词条解释,爬取完毕。

output.html:

这只是最简单的爬虫,如果想深入学习,还有登录、验证码、Ajax、服务器防爬虫、多线程、分布式等等。

GitHub:https://github.com/AbelSu131/baike_spider

Python开发简单爬虫的更多相关文章

  1. Python开发简单爬虫 - 慕课网

    课程链接:Python开发简单爬虫 环境搭建: Eclipse+PyDev配置搭建Python开发环境 Python入门基础教程 用Eclipse编写Python程序   课程目录 第1章 课程介绍 ...

  2. Python开发简单爬虫(一)

    一 .简单爬虫架构: 爬虫调度端:启动爬虫,停止爬虫,监视爬虫运行情况 URL管理器:对将要爬取的和已经爬取过的URL进行管理:可取出带爬取的URL,将其传送给“网页下载器” 网页下载器:将URL指定 ...

  3. Python开发简单爬虫(二)---爬取百度百科页面数据

    一.开发爬虫的步骤 1.确定目标抓取策略: 打开目标页面,通过右键审查元素确定网页的url格式.数据格式.和网页编码形式. ①先看url的格式, F12观察一下链接的形式;② 再看目标文本信息的标签格 ...

  4. Python 开发轻量级爬虫05

    Python 开发轻量级爬虫 (imooc总结05--网页下载器) 介绍网页下载器 网页下载器是将互联网上url对应的网页下载到本地的工具.因为将网页下载到本地才能进行后续的分析处理,可以说网页下载器 ...

  5. Python 开发轻量级爬虫03

    Python 开发轻量级爬虫 (imooc总结03--简单的爬虫架构) 现在来看一下一个简单的爬虫架构. 要实现一个简单的爬虫,有哪些方面需要考虑呢? 首先需要一个爬虫调度端,来启动爬虫.停止爬虫.监 ...

  6. Python 开发轻量级爬虫01

    Python 开发轻量级爬虫 (imooc总结01--课程目标) 课程目标:掌握开发轻量级爬虫 为什么说是轻量级的呢?因为一个复杂的爬虫需要考虑的问题场景非常多,比如有些网页需要用户登录了以后才能够访 ...

  7. Python 开发轻量级爬虫08

    Python 开发轻量级爬虫 (imooc总结08--爬虫实例--分析目标) 怎么开发一个爬虫?开发一个爬虫包含哪些步骤呢? 1.确定要抓取得目标,即抓取哪些网站的哪些网页的哪部分数据. 本实例确定抓 ...

  8. Python 开发轻量级爬虫07

    Python 开发轻量级爬虫 (imooc总结07--网页解析器BeautifulSoup) BeautifulSoup下载和安装 使用pip install 安装:在命令行cmd之后输入,pip i ...

  9. Python 开发轻量级爬虫06

    Python 开发轻量级爬虫 (imooc总结06--网页解析器) 介绍网页解析器 将互联网的网页获取到本地以后,我们需要对它们进行解析才能够提取出我们需要的内容. 也就是说网页解析器是从网页中提取有 ...

随机推荐

  1. js-ES6学习笔记-Promise对象(2)

    1.Promise实例具有then方法,也就是说,then方法是定义在原型对象Promise.prototype上的.它的作用是为Promise实例添加状态改变时的回调函数. 2.Promise.pr ...

  2. apt-get update 系列作用

    sudo apt-get update 更新源 sudo apt-get upgrade 更新已安装的包 sudo apt-get dist-upgrade 升级系统 下面摘自知乎用户回答: apt- ...

  3. 大数据时代,银行BI应用的方案探讨

    大数据被誉为21世纪发展创造的新动力,BI(商业智能)成为当下最热门的数据应用方案.据资料显示:当前中国大数据IT投资最高的为五个行业中,互联网最高.其次是电信.金融.政府和医疗.而在金融行业中,银行 ...

  4. MariaDB MySQL变量取值避免四舍五入的方法

    MySQL变量取值避免四舍五入的方法 By:授客 QQ:1033553122 在一些对数据精确度要求比较高的场景(比如资金结算)下,变量取值时不能对变量值进行四舍五入操作,这时候就要做些预处理工作. ...

  5. Android开发工具Android Studio、Android SDK和Genymotion完全配置

    所谓“工欲善其事,必先利其器”.Android Studio 是谷歌推出一个Android集成开发工具,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提 ...

  6. RecyclerView--添加头部和底部

    1.先构建WrapRecyclerAdapter /** * Description: 可以添加头部和底部的Adapter */ public class WrapRecyclerAdapter ex ...

  7. 解决VB6.0中不能加载MSCOMCTL.OCX的错误提示

    VB6.0毕竟是很古老的开发工具了,其对所使用的第三方组件依赖性比较强,例如在打开从其它电脑上拿来的VB6.0的软件(系统)的工程文件(源代码)时,经常会遇到"不能加载MSCOMCTL.OC ...

  8. __MySQL 5.7 Replication 相关新功能说明

      背景: MySQL5.7在主从复制上面相对之前版本多了一些新特性,包括多源复制.基于组提交的并行复制.在线修改Replication Filter.GTID增强.半同步复制增强等.因为都是和复制相 ...

  9. 推荐一个国外C开发的PHP框架--Phalcon,性能相当好

    本人亲自配置测试后.性能相当不错.不过有一点.使用极不符合国人习惯,甚至和大多数主流PHP框架如Zend Framework,Yii,Ci,Thinkphp都不一样. Phalcon 是一个开源的,全 ...

  10. django导入自定义模块

    自定义模块cust.py位于应用aptest目录下 1.编辑settings.py from aptest import cust 2.编辑views.py from cust import pc # ...