Python之Scrapy爬虫框架安装及简单使用
题记:早已听闻python爬虫框架的大名。近些天学习了下其中的Scrapy爬虫框架,将自己理解的跟大家分享。有表述不当之处,望大神们斧正。
一、初窥Scrapy
Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。
其最初是为了 页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。
本文档将通过介绍Scrapy背后的概念使您对其工作原理有所了解, 并确定Scrapy是否是您所需要的。
当您准备好开始您的项目后,您可以参考 入门教程 。
二、Scrapy安装介绍
Scrapy框架运行平台及相关辅助工具
- Python 2.7(Python最新版3.5,这里选择了2.7版本)
- Python Package: pip and setuptools. 现在 pip 依赖 setuptools ,如果未安装,则会自动安装setuptools 。
- lxml. 大多数Linux发行版自带了lxml。如果缺失,请查看http://lxml.de/installation.html
- 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版本。(如图所示)

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、文件目录结构如下:
。
解析scrapy框架结构:
scrapy.cfg: 项目的配置文件。tutorial/: 该项目的python模块。之后您将在此加入代码。tutorial/items.py: 项目中的item文件。tutorial/pipelines.py: 项目中的pipelines文件。tutorial/settings.py: 项目的设置文件。tutorial/spiders/: 放置spider代码的目录。
3、编写简单的爬虫
1、在item.py中配置需采集页面的字段实例。
# -*- coding: utf- -*- # 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爬虫框架安装及简单使用的更多相关文章
- windows下使用python的scrapy爬虫框架,爬取个人博客文章内容信息
scrapy作为流行的python爬虫框架,简单易用,这里简单介绍如何使用该爬虫框架爬取个人博客信息.关于python的安装和scrapy的安装配置请读者自行查阅相关资料,或者也可以关注我后续的内容. ...
- Python之Scrapy爬虫框架 入门实例(一)
一.开发环境 1.安装 scrapy 2.安装 python2.7 3.安装编辑器 PyCharm 二.创建scrapy项目pachong 1.在命令行输入命令:scrapy startproject ...
- 【python】Scrapy爬虫框架入门
说明: 本文主要学习Scrapy框架入门,介绍如何使用Scrapy框架爬取页面信息. 项目案例:爬取腾讯招聘页面 https://hr.tencent.com/position.php?&st ...
- Python使用Scrapy爬虫框架全站爬取图片并保存本地(妹子图)
大家可以在Github上clone全部源码. Github:https://github.com/williamzxl/Scrapy_CrawlMeiziTu Scrapy官方文档:http://sc ...
- 【网络爬虫】【python】网络爬虫(四):scrapy爬虫框架(架构、win/linux安装、文件结构)
scrapy框架的学习,目前个人觉得比较详尽的资料主要有两个: 1.官方教程文档.scrapy的github wiki: 2.一个很好的scrapy中文文档:http://scrapy-chs.rea ...
- Python爬虫教程-31-创建 Scrapy 爬虫框架项目
本篇是介绍在 Anaconda 环境下,创建 Scrapy 爬虫框架项目的步骤,且介绍比较详细 Python爬虫教程-31-创建 Scrapy 爬虫框架项目 首先说一下,本篇是在 Anaconda 环 ...
- python3.7.1安装Scrapy爬虫框架
python3.7.1安装Scrapy爬虫框架 环境:win7(64位), Python3.7.1(64位) 一.安装pyhthon 详见Python环境搭建:http://www.runoob.co ...
- 安装scrapy 爬虫框架
安装scrapy 爬虫框架 个人根据学习需要,在Windows搭建scrapy爬虫框架,搭建过程种遇到个别问题,共享出来作为记录. 1.安装python 2.7 1.1下载 下载地址 1.2配置环境变 ...
- Scrapy爬虫框架(实战篇)【Scrapy框架对接Splash抓取javaScript动态渲染页面】
(1).前言 动态页面:HTML文档中的部分是由客户端运行JS脚本生成的,即服务器生成部分HTML文档内容,其余的再由客户端生成 静态页面:整个HTML文档是在服务器端生成的,即服务器生成好了,再发送 ...
随机推荐
- CentOS7.2部署OpenStack(一)—环境准备
1.系统环境 # uname -r 3.10.0-327.el7.x86_64 # cat /etc/redhat-release CentOS Linux release 7.2.1511 (Cor ...
- nvm
nvm install stable #安装最新稳定版 node,现在是 5.0.0 nvm install 4.2.2 #安装 4.2.2 版本 nvm install 0.12.7 #安装 0.1 ...
- clientTop、offsetTop和scrollTop的区分
页可见区域宽: document.body.clientWidth; 网页可见区域高: document.body.clientHeight; 网页可见区域宽: document.body.offse ...
- ubuntu12.04 gitlab搭建
最近在尝试内部搭建gitlab,wiki这些工具...我使用的官网的gitlab-ce包一键安装,自己搭建的ubuntu12.04 server服务器. 分配253地址,放在办公室的小角落. 配置过程 ...
- Linux进阶文件系统管理之RAID
RAID 1.引言 RAID全称Redundant Arrays of Inexpensive Disks / Redundant Arrays of Independent Disks,即独立冗余磁 ...
- ActiveMQ安装
安装环境: 逛网下载最新安装包,ubuntu下解压sudo tar -zxvf xx.tar.启动activeMQ. 报错如下: 原因是没有找到java命令位置,编辑启动配置文件: 再次启动,完成后进 ...
- matplotlib 显示中文 与 latex冲突
如果在使用中文之前包含了使用latex的语法: mpl.rcParams['text.usetex'] = True 将不能正确显示含有中文的图片. 附 显示中文的方法: from matplotli ...
- 从一个复杂的json格式的String内获取某key的值
如题,如何简单的从一个复杂的String格式内获取某个key的值. 例如:从下面String下取到status的值. {"response":{"info":{ ...
- excel解析二维数组结构的excel
public void fileImport(Ufile ufile) throws Exception { String filePath = ufile.getFilePath(); List&l ...
- PHP实现队列及队列原理
看看各语言实现队列的方法:PHP实现队列:第一个元素作为队头,最后一个元素作为队尾 <?php /** * 队列就是这么简单 * * @link http://www.phpddt.com */ ...