使用scrapy实现爬网站例子和实现网络爬虫(蜘蛛)的步骤


Posted in Python onJanuary 23, 2014
#!/usr/bin/env python
# -*- coding: utf-8 -*- 
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from cnbeta.items import CnbetaItem
class CBSpider(CrawlSpider):
    name = 'cnbeta'
    allowed_domains = ['cnbeta.com']
    start_urls = ['https://3water.com']
    rules = (
        Rule(SgmlLinkExtractor(allow=('/articles/.*\.htm', )),
             callback='parse_page', follow=True),
    )
    def parse_page(self, response):
        item = CnbetaItem()
        sel = Selector(response)
        item['title'] = sel.xpath('//title/text()').extract()
        item['url'] = response.url
        return item

实现蜘蛛爬虫步骤

1.实例初级目标:从一个网站的列表页抓取文章列表,然后存入数据库中,数据库包括文章标题、链接、时间

首先生成一个项目:scrapy startproject fjsen
先定义下items,打开items.py:

我们开始建模的项目,我们想抓取的标题,地址和时间的网站,我们定义域为这三个属性。这样做,我们编辑items.py,发现在开放目录目录。我们的项目看起来像这样:

from scrapy.item import Item, Field
class FjsenItem(Item):
    # define the fields for your item here like:
    # name = Field()
    title=Field()
    link=Field()
    addtime=Field()

第二步:定义一个spider,就是爬行蜘蛛(注意在工程的spiders文件夹下),他们确定一个初步清单的网址下载,如何跟随链接,以及如何分析这些内容的页面中提取项目(我们要抓取的网站是http://www.fjsen.com/j/node_94962.htm 这列表的所有十页的链接和时间)。
新建一个fjsen_spider.py,内容如下:

#-*- coding: utf-8 -*-
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from fjsen.items import FjsenItem
class FjsenSpider(BaseSpider):
    name="fjsen"
    allowed_domains=["fjsen.com"]
    start_urls=['http://www.fjsen.com/j/node_94962_'+str(x)+'.htm' for x in range(2,11)]+['http://www.fjsen.com/j/node_94962.htm']
    def parse(self,response):
        hxs=HtmlXPathSelector(response)
        sites=hxs.select('//ul/li')
        items=[]
        for site in sites:
            item=FjsenItem()
            item['title']=site.select('a/text()').extract()
            item['link'] = site.select('a/@href').extract()
            item['addtime']=site.select('span/text()').extract()
            items.append(item)
        return items                 

name:是确定蜘蛛的名称。它必须是独特的,就是说,你不能设置相同的名称不同的蜘蛛。
allowed_domains:这个很明显,就是允许的域名,或者说爬虫所允许抓取的范围仅限这个列表里面的域名。
start_urls:是一个网址列表,蜘蛛会开始爬。所以,第一页将被列在这里下载。随后的网址将生成先后从数据中包含的起始网址。我这里直接是列出十个列表页。
parse():是蜘蛛的一个方法,当每一个开始下载的url返回的Response对象都会执行该函数。
这里面,我抓取每一个列表页中的<ul>下的<li>下的数据,包括title,链接,还有时间,并插入到一个列表中

第三步,将抓取到的数据存入数据库中,这里就得在pipelines.py这个文件里面修改了

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
from os import path
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
class FjsenPipeline(object):    def __init__(self):
        self.conn=None
        dispatcher.connect(self.initialize,signals.engine_started)
        dispatcher.connect(self.finalize,signals.engine_stopped)
    def process_item(self,item,spider):
        self.conn.execute('insert into fjsen values(?,?,?,?)',(None,item['title'][0],'https://3water.com/'+item['link'][0],item['addtime'][0]))
        return item
    def initialize(self):
        if path.exists(self.filename):
            self.conn=sqlite3.connect(self.filename)
        else:
            self.conn=self.create_table(self.filename)
    def finalize(self):
        if self.conn is not None:
            self.conn.commit()
            self.conn.close()
            self.conn=None
    def create_table(self,filename):
        conn=sqlite3.connect(filename)
        conn.execute("""create table fjsen(id integer primary key autoincrement,title text,link text,addtime text)""")
        conn.commit()
        return conn

这里我暂时不解释,先继续,让这个蜘蛛跑起来再说。

第四步:修改setting.py这个文件:将下面这句话加进去

ITEM_PIPELINES=['fjsen.pipelines.FjsenPipeline']

接着,跑起来吧,执行:

scrapy crawl fjsen

就会在目前下生成一个data.sqlite的数据库文件,所有抓取到的数据都会存在这里。
Python 相关文章推荐
python同时给两个收件人发送邮件的方法
Apr 30 Python
Python中使用ElementTree解析XML示例
Jun 02 Python
Python对CSV、Excel、txt、dat文件的处理
Sep 18 Python
django 中的聚合函数,分组函数,F 查询,Q查询
Jul 25 Python
python+Django+pycharm+mysql 搭建首个web项目详解
Nov 29 Python
Windows+Anaconda3+PyTorch+PyCharm的安装教程图文详解
Apr 03 Python
keras小技巧——获取某一个网络层的输出方式
May 23 Python
社区版pycharm创建django项目的方法(pycharm的newproject左侧没有项目选项)
Sep 23 Python
Python实现生成bmp图像的方法
Jun 13 Python
简单介绍Python的第三方库yaml
Jun 18 Python
教你怎么用Python selenium操作浏览器对象的基础API
Jun 23 Python
Python卷积神经网络图片分类框架详解分析
Nov 07 Python
python使用scrapy解析js示例
Jan 23 #Python
php使用递归与迭代实现快速排序示例
Jan 23 #Python
python实现批量转换文件编码(批转换编码示例)
Jan 23 #Python
python写的一个文本编辑器
Jan 23 #Python
python生成指定长度的随机数密码
Jan 23 #Python
python使用beautifulsoup从爱奇艺网抓取视频播放
Jan 23 #Python
python3使用urllib示例取googletranslate(谷歌翻译)
Jan 23 #Python
You might like
php面向对象全攻略 (一) 面向对象基础知识
2009/09/30 PHP
php 计算两个时间戳相隔的时间的函数(小时)
2009/12/18 PHP
一个不易被发现的PHP后门代码解析
2014/07/05 PHP
Yii1.1中通过Sql查询进行的分页操作方法
2017/03/16 PHP
理清PHP在Linxu下执行时的文件权限方法
2017/06/07 PHP
PHP大文件分割分片上传实现代码
2020/12/09 PHP
一个对于js this关键字的问题
2007/01/09 Javascript
锋利的jQuery jQuery中的DOM操作
2010/03/21 Javascript
jQuery EasyUI API 中文文档 - ValidateBox验证框
2011/10/06 Javascript
微信小程序 scroll-view隐藏滚动条详解
2017/01/16 Javascript
Angularjs分页查询的实现
2017/02/24 Javascript
vue如何集成raphael.js中国地图的方法示例
2017/08/15 Javascript
关于Vue背景图打包之后访问路径错误问题的解决
2017/11/03 Javascript
JavaScript中this的全面解析及常见实例
2019/05/14 Javascript
详解将微信小程序接口Promise化并使用async函数
2019/08/05 Javascript
JavaScript适配器模式原理与用法实例详解
2020/03/09 Javascript
jQuery实现高度灵活的表单验证功能示例【无UI】
2020/04/30 jQuery
Python中的集合类型知识讲解
2015/08/19 Python
Python脚本修改阿里云的访问控制列表的方法
2019/03/08 Python
python反编译学习之字节码详解
2019/05/19 Python
python实现随机漫步方法和原理
2019/06/10 Python
python多线程http压力测试脚本
2019/06/25 Python
ipython和python区别详解
2019/06/26 Python
tensorflow ckpt模型和pb模型获取节点名称,及ckpt转pb模型实例
2020/01/21 Python
python打开文件的方式有哪些
2020/06/29 Python
python使用隐式循环快速求和的实现示例
2020/09/11 Python
css3边框_动力节点Java学院整理
2017/07/11 HTML / CSS
萨克斯第五大道的折扣店:Saks Fifth Avenue OFF 5TH
2016/08/25 全球购物
DJI大疆德国官方商城:大疆无人机
2018/09/01 全球购物
美国在线和移动免费会员制批发零售商:Boxed(移动端的Costco)
2020/01/02 全球购物
计算机维护专业推荐信
2014/02/27 职场文书
安全生产演讲稿
2014/05/09 职场文书
群众路线教育实践活动整改落实情况汇报
2014/10/28 职场文书
2014年办公室主任工作总结
2014/11/12 职场文书
2014年班组建设工作总结
2014/12/01 职场文书
外出培训学习心得体会
2016/01/18 职场文书