一 安装

  #Linux:

      pip3 install scrapy

  #Windows:

      a. pip3 install wheel

      b. 下载twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

      c. 进入下载目录,执行 pip3 install Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whl

      d. pip3 install pywin32

      e. pip3 install scrapy

二 实验要求

目标网站: http://quotes.toscrape.com/tag/humor/

任务:保存网页信息到本地

二 创建爬虫项目

scrapy startproject tutorial

生成项目的结构

tutorial/
scrapy.cfg # 部署配置文件 tutorial/ # 项目的Python模块,你将从这里导入你的代码
__init__.py items.py # 项目项目定义文件,用于规定存储的字段 middlewares.py # 项目中间件文件 pipelines.py # 项目持久化存储文件 settings.py # 项目配置文件 spiders/ # 这里可以创建爬虫文件        .        # 若干个爬虫文件
       .
       .
__init__.py

三 创建爬虫文件

scrapy genspider QuotesSpider #爬虫文件名为QuotesSpider 

使用pycharm打开项目,修改QuotesSpider .py 文件改为

# -*- coding: utf-8 -*-
import scrapy class QuotesspiderSpider(scrapy.Spider):
name = 'QuotesSpider' #爬虫名字 def start_requests(self):
#待爬取的url列表
urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
for url in urls:
#提交请求,并制定回调函数为self.parse
yield scrapy.Request(url=url, callback=self.parse) def parse(self, response):
'解析页面,response是网页返回的数据(源码)'
page = response.url.split("/")[-2]
filename = 'quotes-%s.html' % page
# 网页保存
with open(filename, 'wb') as f:
f.write(response.body)
self.log('Saved file %s' % filename)

其中

  name: 爬虫名字,项目中名字是唯一的.

  start_requests():必须返回一个可迭代的对象.爬取起始url网页.指定回调函数.

  parse():解析页面数据,

四 启动爬虫文件

scrapy crawl QuotesSpider

效果展示

五 项目执行流程

  Scrapy 执行的时候,首先会调用start_requests方法,然后执行方法中的scrapy.Request方法获取url对应网站的数据,得到Response相应对象,转而把Response对象交给Scrapy.Request的回调函数,在回调函数中解析response对象中的网页源码数据,保存到当前目录下.

六  Scrapy shell

  使用Scrapy提取数据的最佳方法时使用scrapy shell 常识选择器.

scrapy shell "http://quotes.toscrape.com/page/1/"

执行此命令后可以进入交互模式(如下):

解析可选参数

[s] Available Scrapy objects:

[s]   scrapy     # 可以使用scrapy中的模块,如contains scrapy.Request, scrapy.Selector...

[s] crawler # 当前爬虫对象
[s] item {}
[s] request #当前的请求页面
[s] response #当前请求的响应
[s] settings # 当前的配置文件
[s] spider <DefaultSpider 'default' at 0x7fa91c8af990> [s] Useful shortcuts:
[s] shelp() Shell help (print this help)
[s] fetch(req_or_url) # 爬取url或者request获取新的response
[s] view(response) # 使用网页打开response

使用栗子:

>>> response.css('title::text').getall() #获取标题中提取文本
['Quotes to Scrape']

七 scrapy 中的数据解析

  Scrapy带有自己的提取数据机制。它们被称为选择器,因为它们“选择”由XPathCSS表达式指定的HTML文档的某些部分。

测试代码

'''

<html>
<head>
<base href='http://example.com/' />
<title>Example website</title>
</head>
<body>
<div id='images'>
<a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
<a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
<a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
<a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
<a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
</div>
</body>
</html>

'''

1 css解析器

>>> response.css('title').getall() #获取所有的匹配结果
['<title>Quotes to Scrape</title>']
>>> response.css('title::text')[0].get() #获取第一个匹配结果
'Quotes to Scrape'

使用正则匹配结果

>>> response.css('title::text').re(r'Quotes.*')
['Quotes to Scrape'] >>> response.css('title::text').re(r'Q\w+')
['Quotes'] >>> response.css('title::text').re(r'(\w+) to (\w+)')
['Quotes', 'Scrape']

2 xpath 解析数据

>>> response.xpath('//title')
[<Selector xpath='//title' data='<title>Quotes to Scrape</title>'>]
>>> response.xpath('//title/text()').get()
'Quotes to Scrape'

  注意:scrapy使用xpath解析出来的数据返回的是select对象,一般提取数据信息的方法如下

# 获取第一个元素
author = div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
# 获取第一个元素
author = div.xpath('./div[1]/a[2]/h2/text()').extract_first() #获取所有元素,结果为一个列表
content = div.xpath('./a[1]/div/span//text()').extract()

现在我们将获得基本URL和一些图像链接:

>>> response.xpath('//base/@href').get()
'http://example.com/' >>> response.css('base::attr(href)').get()
'http://example.com/' >>> response.css('base').attrib['href']
'http://example.com/' >>> response.xpath('//a[contains(@href, "image")]/@href').getall()
['image1.html',
'image2.html',
'image3.html',
'image4.html',
'image5.html'] >>> response.css('a[href*=image]::attr(href)').getall()
['image1.html',
'image2.html',
'image3.html',
'image4.html',
'image5.html'] >>> response.xpath('//a[contains(@href, "image")]/img/@src').getall()
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg'] >>> response.css('a[href*=image] img::attr(src)').getall()
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg']

最后归纳:

获取元素中的文本推荐使用

  • get( ) #获取第一个值
  • getall( ) #获取所有,返回列表

八 调整代码进行所有页面数据爬取

# -*- coding: utf-8 -*-
import scrapy class QuotesspiderSpider(scrapy.Spider):
name = 'QuotesSpider' start_urls = [
'http://quotes.toscrape.com/page/1/',
] def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('small.author::text').get(),
'tags': quote.css('div.tags a.tag::text').getall(),
}
#获取下一页的url
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
#urljoin用于构建下一页的绝对路径url
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)

  使用css选择器获取下一页的url(相对路径),在使用response.urljoin()获取绝对路径,再次回调self.parse()实现所有页面数据爬取.

九 scrapy 文件输出参数

scrapy crawl quotes -o quotes-humor.json 
'''
  - o 把详情页返回结果,输入到文件
'''

初始scrapy,简单项目创建和CSS选择器,xpath选择器(1)的更多相关文章

  1. 王立平--java se的简单项目创建以及具体解释

    创建项目的简单步骤: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzQyNTUyNw==/font/5a6L5L2T/fontsize/400/ ...

  2. cube.js 学习(一)简单项目创建

    cube.js 是一个很不错的模块化分析框架,基于schema生成sql 同时内置可代码生成,可以快速的搞定 web 分析应用的开发 安装cli 工具 npm install -g cubejs-cl ...

  3. Spring Cloud简单项目创建

    一.Zuul 原文链接 Zuul的主要功能是路由转发和过滤器.路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务.zuul默认和Ribbon结 ...

  4. 从0开始,手把手教你用Vue开发一个答题App01之项目创建及答题设置页面开发

    项目演示 项目演示 项目源码 项目源码 教程说明 本教程适合对Vue基础知识有一点了解,但不懂得综合运用,还未曾使用Vue从头开发过一个小型App的读者.本教程不对所有的Vue知识点进行讲解,而是手把 ...

  5. scrapy简单入门及选择器(xpath\css)

    简介 scrapy被认为是比较简单的爬虫框架,资料比较齐全,网上也有很多教程.官网上介绍了它的四种安装方法,PyPI.Conda.APT.Source,我们只介绍最简单的安装方法. 安装 Window ...

  6. Python -- Scrapy 框架简单介绍(Scrapy 安装及项目创建)

    Python -- Scrapy 框架简单介绍 最近在学习python 爬虫,先后了解学习urllib.urllib2.requests等,后来发现爬虫也有很多框架,而推荐学习最多就是Scrapy框架 ...

  7. Windows 8.1 应用再出发 (WinJS) - 创建一个简单项目

    前面几篇我们介绍了如何利用 C# + XAML 完成Windows Store App 功能的实现,接下来的几篇我们来看看如何利用 Html + WinJS 来完成这些功能. 本篇我们使用WinJS ...

  8. python爬虫框架—Scrapy安装及创建项目

    linux版本安装 pip3 install scrapy 安装完成 windows版本安装 pip install wheel 下载twisted,网址:http://www.lfd.uci.edu ...

  9. m2eclipse简单使用,创建Maven项目 ,运行mvn命令(转)

    前面介绍了如何安装m2eclipse,现在,我们使用m2ecilpse导入Hello World项目. 选择菜单项File,然后选择Import,我们会看到一个Import对话框,在该对话框中选择Ge ...

随机推荐

  1. springCloud系列 Config配置中心

    1.config服务的部署 2.yum文件的格式 大小写敏感 使用缩进表示层级关系 缩进时不允许使用Tab键,只允许使用空格. 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可 3.热部署 4.配 ...

  2. Tiny4412之外部中断

    一:外部中断 在之前我们学习按键驱动的时候,我们检测按键有没有按下是通过轮循的方式(也就是我们说的死循环),这样虽然可以检测实现按键,但太浪费系统资源了,不论我们按键中断有没有发生,cpu都要一直进行 ...

  3. MATCH_PARENT和FILL_PARENT之间的区别?

    很多人表示对于很多工程中的MATCH_PARENT出现在layout中感到不明白,过去只有FILL_PARENT和WRAP_CONTENT那么 match_parent到底是什么类型呢? 其实从And ...

  4. 你不知道的JavaScript--Item27 异步编程异常解决方案

    1.JavaScript异步编程的两个核心难点 异步I/O.事件驱动使得单线程的JavaScript得以在不阻塞UI的情况下执行网络.文件访问功能,且使之在后端实现了较高的性能.然而异步风格也引来了一 ...

  5. C. Liebig's Barrels

    You have m = n·k wooden staves. The i-th stave has length ai. You have to assemble nbarrels consisti ...

  6. Selenium 三种等待

    问题 : 强制等待和隐式等待的区别怎么理解? 和pause有什么区别?什么时候适用pause? 第二篇文章更清楚一点. 以下内容引自: https://www.cnblogs.com/xu-jia-l ...

  7. 知识点:java一些方法会有横线?以Date 过期方法为例

    原因:他们的开发者在升级方法后,添加了@Deprecated注释, 目的是为了提醒我们,这个方法现在已经有新的方法了,不建议继续使用! 比如: JAVA中Date的tolocalstring为什么不建 ...

  8. System.out.println()

    System是java.lang中的类,out为System中的一个静态数据成员,out是java.io.PrintStream类的对象,而println()是java.io.PrintStream类 ...

  9. 时序数据库InfluxDB使用详解

    1 安装配置 这里说一下使用docker容器运行influxdb的步骤,物理机安装请参照官方文档.拉取镜像文件后运行即可,当前最新版本是1.3.5.启动容器时设置挂载的数据目录和开放端口.Influx ...

  10. 打包前端WebSite到Go程序

    打包前端WebSite到Go程序 Coolpy5发布在即,新版本要求服务端程序只是一个运行文件,经历了go的template无数坑后,最后还是放弃了,所以还是要把前端独立开发一个纯前端程序,但是go程 ...