Python之Scrapy爬虫框架安装及简单使用详解


Posted in Python onDecember 22, 2017

题记:早已听闻python爬虫框架的大名。近些天学习了下其中的Scrapy爬虫框架,将自己理解的跟大家分享。有表述不当之处,望大神们斧正。

一、初窥Scrapy

Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。

其最初是为了页面抓取(更确切来说,网络抓取)所设计的, 也可以应用在获取API所返回的数据(例如Amazon Associates Web Services) 或者通用的网络爬虫。

本文档将通过介绍Scrapy背后的概念使您对其工作原理有所了解, 并确定Scrapy是否是您所需要的。

当您准备好开始您的项目后,您可以参考入门教程。

二、Scrapy安装介绍

Scrapy框架运行平台及相关辅助工具

  1. Python2.7(Python最新版3.5,这里选择了2.7版本)
  2. Python Package:pipandsetuptools. 现在pip依赖setuptools,如果未安装,则会自动安装setuptools。
  3. lxml. 大多数Linux发行版自带了lxml。如果缺失,请查看http://lxml.de/installation.html
  4. OpenSSL. 除了Windows(请查看平台安装指南)之外的系统都已经提供。

您可以使用pip来安装Scrapy(推荐使用pip来安装Python package).

pip install Scrapy

Windows下安装流程:

1、安装Python 2.7之后,您需要修改PATH环境变量,将Python的可执行程序及额外的脚本添加到系统路径中。将以下路径添加到PATH中:

C:\Python27\;C:\Python27\Scripts\;

除此之外,还可以用cmd命令来设置Path:

c:\python27\python.exe c:\python27\tools\scripts\win_add2path.py

安装配置完成之后,可以执行命令python --version查看安装的python版本。(如图所示)

Python之Scrapy爬虫框架安装及简单使用详解

2、从http://sourceforge.net/projects/pywin32/安装pywin32

请确认下载符合您系统的版本(win32或者amd64)

从https://pip.pypa.io/en/latest/installing.html安装pip

3、打开命令行窗口,确认pip被正确安装:

pip --version

4、到目前为止Python 2.7 及pip已经可以正确运行了。接下来安装Scrapy:

pip install Scrapy

至此windows下Scrapy安装已经结束。

三、Scrapy入门教程

1、在cmd中创建Scrapy项目工程。

scrapy startproject tutorial

H:\python\scrapyDemo>scrapy startproject tutorial
New Scrapy project 'tutorial', using template directory 'f:\\python27\\lib\\site-packages\\scrapy\\templates\\project', created in:
  H:\python\scrapyDemo\tutorial

You can start your first spider with:
  cd tutorial
  scrapy genspider example example.com

2、文件目录结构如下:

Python之Scrapy爬虫框架安装及简单使用详解

解析scrapy框架结构:

  1. scrapy.cfg: 项目的配置文件。
  2. tutorial/: 该项目的python模块。之后您将在此加入代码。
  3. tutorial/items.py: 项目中的item文件。
  4. tutorial/pipelines.py: 项目中的pipelines文件。
  5. tutorial/settings.py: 项目的设置文件。
  6. tutorial/spiders/: 放置spider代码的目录。

3、编写简单的爬虫

1、在item.py中配置需采集页面的字段实例。

# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
class TutorialItem(Item):
  title = Field()
  author = Field()
  releasedate = Field()

2、在tutorial/spiders/spider.py中书写要采集的网站以及分别采集各字段。

# -*-coding:utf-8-*-
import sys
from scrapy.linkextractors.sgml import SgmlLinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from tutorial.items import TutorialItem
reload(sys)
sys.setdefaultencoding("utf-8")
class ListSpider(CrawlSpider):
  # 爬虫名称
  name = "tutorial"
  # 设置下载延时
  download_delay = 1
  # 允许域名
  allowed_domains = ["news.cnblogs.com"]
  # 开始URL
  start_urls = [
    "https://news.cnblogs.com"
  ]
  # 爬取规则,不带callback表示向该类url递归爬取
  rules = (
    Rule(SgmlLinkExtractor(allow=(r'https://news.cnblogs.com/n/page/\d',))),
    Rule(SgmlLinkExtractor(allow=(r'https://news.cnblogs.com/n/\d+',)), callback='parse_content'),
  )

  # 解析内容函数
  def parse_content(self, response):
    item = TutorialItem()

    # 当前URL
    title = response.selector.xpath('//div[@id="news_title"]')[0].extract().decode('utf-8')
    item['title'] = title

    author = response.selector.xpath('//div[@id="news_info"]/span/a/text()')[0].extract().decode('utf-8')
    item['author'] = author

    releasedate = response.selector.xpath('//div[@id="news_info"]/span[@class="time"]/text()')[0].extract().decode(
      'utf-8')
    item['releasedate'] = releasedate

    yield item

3、在tutorial/pipelines.py管道中保存数据。

# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import codecs
class TutorialPipeline(object):
  def __init__(self):
    self.file = codecs.open('data.json', mode='wb', encoding='utf-8')#数据存储到data.json

  def process_item(self, item, spider):
    line = json.dumps(dict(item)) + "\n"
    self.file.write(line.decode("unicode_escape"))

    return item

4、tutorial/settings.py中配置执行环境。

# -*- coding: utf-8 -*-
BOT_NAME = 'tutorial'
SPIDER_MODULES = ['tutorial.spiders']
NEWSPIDER_MODULE = 'tutorial.spiders'

# 禁止cookies,防止被ban
COOKIES_ENABLED = False
COOKIES_ENABLES = False

# 设置Pipeline,此处实现数据写入文件
ITEM_PIPELINES = {
  'tutorial.pipelines.TutorialPipeline': 300
}

# 设置爬虫爬取的最大深度
DEPTH_LIMIT = 100

5、新建main文件执行爬虫代码。

from scrapy import cmdline
cmdline.execute("scrapy crawl tutorial".split())

最终,执行main.py后在data.json文件中获取到采集结果的json数据。

Python之Scrapy爬虫框架安装及简单使用详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
从Python的源码来解析Python下的freeblock
May 11 Python
Python 2与Python 3版本和编码的对比
Feb 14 Python
Python实现学生成绩管理系统
Apr 05 Python
Python实现判断并移除列表指定位置元素的方法
Apr 13 Python
使用python读取txt文件的内容,并删除重复的行数方法
Apr 18 Python
Django使用AJAX调用自己写的API接口的方法
Mar 06 Python
Python爬取腾讯视频评论的思路详解
Dec 19 Python
tensorflow ckpt模型和pb模型获取节点名称,及ckpt转pb模型实例
Jan 21 Python
Ubuntu18.04安装 PyCharm并使用 Anaconda 管理的Python环境
Apr 08 Python
keras读取训练好的模型参数并把参数赋值给其它模型详解
Jun 15 Python
通过实例解析python创建进程常用方法
Jun 19 Python
django rest framework 过滤时间操作
Jul 12 Python
Python2.7下安装Scrapy框架步骤教程
Dec 22 #Python
Python机器学习之决策树算法
Dec 22 #Python
python+selenium实现登录账户后自动点击的示例
Dec 22 #Python
python实现决策树
Dec 21 #Python
python利用sklearn包编写决策树源代码
Dec 21 #Python
python实现决策树分类算法
Dec 21 #Python
Python语言描述机器学习之Logistic回归算法
Dec 21 #Python
You might like
让php处理图片变得简单 基于gb库的图片处理类附实例代码下载
2011/05/17 PHP
用PHP实现小写金额转换大写金额的代码(精确到分)
2012/01/10 PHP
php数组合并array_merge()函数使用注意事项
2014/06/19 PHP
PHP读取配置文件类实例(可读取ini,yaml,xml等)
2015/07/28 PHP
php版交通银行网银支付接口开发入门教程
2016/09/26 PHP
jQuery入门第一课 jQuery选择符
2010/03/14 Javascript
html+css+js实现xp window界面及有关功能
2013/03/26 Javascript
js取float型小数点后两位数的方法
2014/01/18 Javascript
js特殊字符过滤的示例代码
2014/03/05 Javascript
jQuery实现数字加减效果汇总
2014/12/16 Javascript
jQuery中fadeOut()方法用法实例
2014/12/24 Javascript
JS仿hao123导航页面图片轮播效果
2016/09/01 Javascript
微信小程序 动态绑定数据及动态事件处理
2017/03/14 Javascript
JS/CSS实现字符串单词首字母大写功能
2019/09/03 Javascript
小程序接口的promise化的实现方法
2019/12/11 Javascript
JavaScript事件冒泡机制原理实例解析
2020/01/14 Javascript
基于vue的tab-list类目切换商品列表组件的示例代码
2020/02/14 Javascript
vue实现编辑器键盘抬起时内容跟随光标距顶位置向上滚动效果
2020/05/28 Javascript
[01:32]dota2拉比克至宝(222)
2018/12/20 DOTA
python读取excel指定列数据并写入到新的excel方法
2018/07/10 Python
python实现抠图给证件照换背景源码
2019/08/20 Python
keras 实现轻量级网络ShuffleNet教程
2020/06/19 Python
css3设置box-pack和box-align让div里面的元素垂直居中
2014/09/01 HTML / CSS
纯css3实现的竖形无限级导航
2014/12/10 HTML / CSS
捷克领先的户外服装及配件市场零售商:ALPINE PRO
2018/01/09 全球购物
门卫工作岗位职责
2013/12/17 职场文书
职业生涯规划书基本格式
2014/01/06 职场文书
消防器材管理制度
2014/01/28 职场文书
护理专业求职信
2014/06/15 职场文书
社区平安建设汇报材料
2014/08/14 职场文书
铅球加油稿100字
2014/09/26 职场文书
领导干部作风整顿剖析材料
2014/10/11 职场文书
大学生上课迟到检讨书
2014/10/15 职场文书
好媳妇事迹材料
2014/12/24 职场文书
关于运动会的广播稿
2015/08/19 职场文书
HTML基础-标签分类(闭合标签,空标签,块级元素,行内元素,行级块元素,可替换元素)
2021/03/31 HTML / CSS