一 安装

  #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. 使用SimHash进行海量文本去重[转载]

    阅读目录 1. SimHash与传统hash函数的区别 2. SimHash算法思想 3. SimHash流程实现 4. SimHash签名距离计算 5. SimHash存储和索引 6. SimHas ...

  2. Linux内核参数调优

    用法: vim /etc/sysctl.conf #修改内容 sysctl -p #生效 相关参数仅供参考,具体数值还需要根据机器性能,应用场景等实际情况来做更细微调整.   net.core.net ...

  3. Java JWT: JSON Web Token

    Java JWT: JSON Web Token for Java and Android JJWT aims to be the easiest to use and understand libr ...

  4. pymysql安装

    安装python3之后 链接数据库需要安装pymysql pymysql 下载地址 https://pypi.python.org/pypi/PyMySQL3/0.5 ,下载之后传到linux虚拟机, ...

  5. 富文本编辑器UEditor自定义工具栏(三、自定义工具栏功能按钮图标及工具栏样式简单修改)

    导读 富文本编辑器UEditor提供丰富了定制配置项,如果想设置个性化的工具栏按钮图标有无办法呢?答案是肯定的!前两篇博文简要介绍了通过将原工具栏隐藏,在自定义的外部按钮上,调用UEditor各命令实 ...

  6. 在腾讯云(windows)上搭建node.js服务器

    1:安装Node.js 使用MSI文件,并按照提示安装node.js,默认情况下,安装程序将 Node.js 发行到 C:\Program Files\nodejs. 但这里我们需要修改安装路径到:D ...

  7. openfire推送离线聊天信息的插件

    插件说明 在手机的聊天应用中,经常出现的一个需求就是把用户的离线消息通过推送系统推送到用户的手机上,为了实现这个功能,本人就开发了本插件,这个openfire 插件是拦截了发给openfire用户的离 ...

  8. Python3 模拟登录知乎(requests)

    # -*- coding: utf-8 -*- """ 知乎登录分为两种登录 一是手机登录 API : https://www.zhihu.com/login/phone ...

  9. orcl数据库命令行怎么导入dmp格式的文件

    2018-05-23 1.创建空间 以system的身份登陆orcl 打开SQL Window界面,输入以下命令create tablespace SGXC(表空间的名字)datafile 'D:/S ...

  10. python接口自动化(十八)--重定向(Location)(详解)

    简介 在实际工作中,有些接口请求完以后会重定向到别的url,而你却需要重定向前的url.URL主要是针对虚拟空间而言,因为不是自己独立管理的服务器,所以无法正常进行常规的操作.但是自己又不希望通过主域 ...