Scrapy抓取Quotes to Scrape
# 爬虫主程序quotes.py
# -*- coding: utf-8 -*-
import scrapy
from quotetutorial.items import QuoteItem
# 启动爬虫
# 请求都是默认的,我们不需要管请求的操作,只要关心解析的过程就可以了
class QuotesSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["quotes.toscrape.com"]
start_urls = ['http://quotes.toscrape.com/']
# python默认执行了相当一部分操作,比如这里,有了start_urls以后,会默认启用start_requests方法,该方法遍历得到每一个url,并且调用make_requests_from_url进行请求,返回response给parse函数
# 请求得到的结果,回调给parse,response即相应结果
def parse(self, response):
quotes = response.css('.quote')
for quote in quotes:
# 如果只有一个内容,可以用extract_first,如果有多个内容可以用extract全部提取出来
# 可以用scrapy-conda shell quotes.toscrape.com 进入到命令行交互模式下
item = QuoteItem()
text = quote.css('.text::text').extract_first()
author = quote.css('.author::text').extract_first()
tags = quote.css('.tags .tag::text').extract()
item['text'] = text
item['author'] = author
item['tags'] = tags
yield item
# 获取下一页的相对url
next = response.css('.pager .next a::attr(href)').extract_first()
# 拼接成绝对url
url = response.urljoin(next)
#递归调用,循环打开下一页
yield scrapy.Request(url = url, callback=self.parse)
# 可以用scrapy-conda crawl quotes -o 文件名+扩展名
# quotes.json/quotes.jl/quotes.csv/quotes.pickle/quotes.xml/quotes.marshal导出各种格式
# ftp://user:pass@ftp.exampel.com/path/quotes.csv 可以远程ftp保存
# items定义的项目数据结构
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
# items相当于定义一个数据结构,给它指定一个个字段,比如标题,图片,文本内容等
import scrapy class QuoteItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()
# 中间储藏环节middlewares.py
# -*- coding: utf-8 -*- # Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy import signals class QuotetutorialSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects. @classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s def process_spider_input(response, spider):
# Called for each response that goes through the spider
# middleware and into the spider. # Should return None or raise an exception.
return None def process_spider_output(response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response. # Must return an iterable of Request, dict or Item objects.
for i in result:
yield i def process_spider_exception(response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception. # Should return either None or an iterable of Response, dict
# or Item objects.
pass def process_start_requests(start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated. # Must return only requests (not items).
for r in start_requests:
yield r def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
# 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
from scrapy.exceptions import DropItem
import pymongo
#判断文本长度是否超过某一界限
class TextPipeline(object):
def __init__(self):
self.limit = 50 def process_item(self, item, spider):
if item['text']:
if len(item['text']) > self.limit:
item['text'] = item['text'][0:self.limit].rstrip() + '...'
return item
else:
return DropItem('Missing Text') class MongoPipeline(object):
def __init__(self, mongo_url,mongo_db):
self.mongo_url = mongo_url
self.mongo_db = mongo_db @classmethod
def from_crawler(cls,crawler):
return cls(
mongo_url = crawler.settings.get('MONGO_URL'),
mongo_db = crawler.settings.get('MONGO_DB')
)
# mongodb的初始化对象
def open_spider(self,spider):
self.client = pymongo.MongoClient(self.mongo_url)
self.db = self.client[self.mongo_db] # 保存到mongodb
def process_item(self, item, spider):
name = item.__class__.__name__
self.db[name].insert(dict(item))
return item #千万要注意,这里不要忘了返回,否则就会显示None
def close_spider(self,spider):
self.client.close()
# 配置文件
# -*- coding: utf-8 -*- # Scrapy settings for quotetutorial project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'quotetutorial' SPIDER_MODULES = ['quotetutorial.spiders']
NEWSPIDER_MODULE = 'quotetutorial.spiders'
MONGO_URL = 'localhost'
MONGO_DB = 'quotetutorial' # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'quotetutorial (+http://www.yourdomain.com)' # Obey robots.txt rules
ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default)
#COOKIES_ENABLED = False # Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False # Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#} # Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'quotetutorial.middlewares.QuotetutorialSpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'quotetutorial.middlewares.MyCustomDownloaderMiddleware': 543,
#} # Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#} # Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
# 'quotetutorial.pipelines.TextPipeline': 300,
'quotetutorial.pipelines.MongoPipeline': 400,
} # Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# 利用scrapy爬取quotes.toscrape.com网站
# 第一步,分析目标网站,确定数据结构,即要爬取的项目构成.去items里面设置对应项目
# 第二步,爬取首页信息,分析首页,提取项目items
# 第三步,首页抓取下一页信息,循环递归调用request请求,实现翻页爬取
# 第四步,修改settings,pipelines等,实现对items的修改,清洗,梳理以及存储
Scrapy抓取Quotes to Scrape的更多相关文章
- 通过Scrapy抓取QQ空间
毕业设计题目就是用Scrapy抓取QQ空间的数据,最近毕业设计弄完了,来总结以下: 首先是模拟登录的问题: 由于Tencent对模拟登录比较讨厌,各个防备,而本人能力有限,所以做的最简单的,手动登录后 ...
- python scrapy 抓取脚本之家文章(scrapy 入门使用简介)
老早之前就听说过python的scrapy.这是一个分布式爬虫的框架,可以让你轻松写出高性能的分布式异步爬虫.使用框架的最大好处当然就是不同重复造轮子了,因为有很多东西框架当中都有了,直接拿过来使用就 ...
- scrapy抓取淘宝女郎
scrapy抓取淘宝女郎 准备工作 首先在淘宝女郎的首页这里查看,当然想要爬取更多的话,当然这里要查看翻页的url,不过这操蛋的地方就是这里的翻页是使用javascript加载的,这个就有点尴尬了,找 ...
- scrapy抓取拉勾网职位信息(一)——scrapy初识及lagou爬虫项目建立
本次以scrapy抓取拉勾网职位信息作为scrapy学习的一个实战演练 python版本:3.7.1 框架:scrapy(pip直接安装可能会报错,如果是vc++环境不满足,建议直接安装一个visua ...
- scrapy抓取的中文结果乱码解决办法
使用scrapy抓取的结果,中文默认是Unicode,无法显示中文. 中文默认是Unicode,如: \u5317\u4eac\u5927\u5b66 在setting文件中设置: FEED_EXPO ...
- 分布式爬虫:使用Scrapy抓取数据
分布式爬虫:使用Scrapy抓取数据 Scrapy是Python开发的一个快速,高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据.Scrapy用途广泛,可以用于数据挖掘. ...
- 解决Scrapy抓取中文网页保存为json文件时中文不显示而是显示unicode的问题
注意:此方法跟之前保存成json文件的写法有少许不同之处,注意区分 情境再现: 使用scrapy抓取中文网页,得到的数据类型是unicode,在控制台输出的话也是显示unicode,如下所示 {'au ...
- scrapy抓取中国新闻网新闻
目标说明 利用scrapy抓取中新网新闻,关于自然灾害滑坡的全部国内新闻:要求主题为滑坡类新闻,包含灾害造成的经济损失等相关内容,并结合textrank算法,得到每篇新闻的关键词,便于后续文本挖掘分析 ...
- scrapy抓取斗鱼APP主播信息
如何进行APP抓包 首先确保手机和电脑连接的是同一个局域网(通过路由器转发的网络,校园网好像还有些问题). 1.安装抓包工具Fiddler,并进行配置 Tools>>options> ...
随机推荐
- Object.defineProperty实现数据绑定
1.Object.defineProperty方法 Object.defineProperty(obj, prop, descriptor); (1)参数: obj:目标对象 prop:需要定义的属 ...
- spring boot多环境配置 直接上代码
spring: profiles: active: test jackson: date-format: yyyy-MM-dd HH:mm:ss datasource: dri ...
- STL --> remove和remove_if()
remove和remove_if() 一.Remove()函数 remove(beg,end,const T& value) //移除区间{beg,end)中每一个“与value相等”的元素: ...
- Algorithm --> 最长回文子串
1.中心扩展 中心扩展就是把给定的字符串的每一个字母当做中心,向两边扩展,这样来找最长的子回文串.算法复杂度为O(N^2). 但是要考虑两种情况: 1.像aba,这样长度为奇数. 2.想abba,这样 ...
- jquery easyui+spring mnv 样式引不进,需要加载静态资源
前台用的EasyUI,页面中引入了easyUI的js与css(引入路径正确),但是无论如何都显示不出来, 如下图: EasyUI的样式没有,看控制台:警告,找不到 21:26:25,643 WARN ...
- [bzoj1707]tanning分配防晒霜_贪心+排序
tanning分配防晒霜 bzoj-1707 题目大意:给出每个点所能接受的区间,给出m个可以使单个点固定在一个值的方法,每种方法能使用有限次. 注释:1<=N<=2500 想法:这题是瞎 ...
- iOS 代码开发规范
最近公司因为业务增多,又招了一个iOS小伙伴,内心无比开心呀.但是多了一个人,日常代码开发就要统一规范起来,方便日后维护和查找.下边列一下我日常用到一些代码规范. (一).SVN规范 1.代码一定要先 ...
- Flash Builder4.7安装破解
引用自CSDN博客,日后我会上传FlashBuilder到百度网盘谢谢 http://bbs.csdn.net/topics/391036327
- Comparable接口和Comparator接口
1.一个类在设计之初就要实现对该类对象的排序功能,那么这个类要实现Comparable接口,实现public int compareTo(T t)方法.如代码中的Student类.对于实现Compar ...
- MySQL的学习记录(3.31更新)
MySQL的学习记录(3.31更新) 0x00 安装及配置 Windows 1.首先官网下载(https://dev.mysql.com/downloads/mysql/) ps:不想官网下载的可以到 ...