[scrapy]一个简单的scrapy爬虫demo
一个简单的scrapy爬虫demo
爬取豆瓣top250的电影名称+电影口号
使用到持久化流程:
- 爬虫文件爬取到数据后,需要将数据封装到items对象中。
- 使用yield关键字将items对象提交给pipelines管道进行持久化操作。
- settings.py配置文件中开启管道
同时完成多页爬取
【douban.py】
import scrapy
from ..items import ScPachongItem
class DoubanSpider(scrapy.Spider):
name = 'douban'
start_urls = [
'https://movie.douban.com/top250',
]
allowed_domains = ["douban.com"]
pageNum = 0 # 起始页码
# 爬取多页
url = 'https://movie.douban.com/top250?start={}&filter=' # 每页的url
#解析函数
def parse(self, response):
# xpath为response中的方法,可以将xpath表达式直接作用于该函数中
odiv = response.xpath('//div[@class="item"]')
for div in odiv:
# xpath函数返回的为列表,列表中存放的数据为Selector类型的数据。我们解析到的内容被封装在了Selector对象中,需要调用extract()函数将解析的内容从Selecor中取出。
name = div.xpath('.//span[@class="title"]/text()')[0].extract()
slogan = div.xpath('.//span[@class="inq"]/text()')[0].extract()
item = ScPachongItem()
item['name'] = name
item['slogan'] = slogan
yield item
# 爬取所有页码数据
self.pageNum += 25
if self.pageNum <= 250: # 一共爬取250条数据(共10页)
url = self.url.format(self.pageNum)
# 递归爬取数据:callback参数的值为回调函数(将url请求后,得到的相应数据继续进行parse解析),递归调用parse函数
yield scrapy.Request(url=url, callback=self.parse)
【pipelines.py】
对item的操作可以双路开,
比如保存成data.txt和保存到MySQL中
只需要重新定义一个类
然后在【settings.py】中保存值,就会按照保存值的大小先后进行。
【【值越小,优先级别越高】】
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class ScPachongPipeline:
def __init__(self):
self.fp = None
def open_spider(self,spider):
print('爬虫开始')
self.fp = open('./data.txt', 'w')
def process_item(self, item, spider):
# self.fp.write(item['name'] + '\n')
self.fp.write(item['name'] + ':' + item['slogan'] + '\n')
return item
#结束爬虫时,执行一次
def close_spider(self,spider):
self.fp.close()
print('爬虫结束')
【【两种持久化操作方式】】
#该类为管道类,该类中的process_item方法是用来实现持久化存储操作的。
class DoublekillPipeline(object):
def process_item(self, item, spider):
#持久化操作代码 (方式1:写入磁盘文件)
return item
#如果想实现另一种形式的持久化操作,则可以再定制一个管道类:
class DoublekillPipeline_db(object):
def process_item(self, item, spider):
#持久化操作代码 (方式1:写入数据库)
return item
复制代码
【items.py】
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class ScPachongItem(scrapy.Item):
# define the fields for your item here like:
name = scrapy.Field()
slogan = scrapy.Field()
pass
【settings.py】
在ITEM_PIPELINES中可以调整300、200这种权值大小,调整item存取的先后。
# Scrapy settings for sc_pachong project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'sc_pachong'
SPIDER_MODULES = ['sc_pachong.spiders']
NEWSPIDER_MODULE = 'sc_pachong.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.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 https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'sc_pachong.middlewares.ScPachongSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'sc_pachong.middlewares.ScPachongDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'sc_pachong.pipelines.ScPachongPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.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 https://docs.scrapy.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'
最终爬取结果,保存为data.txt
肖申克的救赎:希望让人自由。
霸王别姬:风华绝代。
阿甘正传:一部美国近现代史。
泰坦尼克号:失去的才是永恒的。
这个杀手不太冷:怪蜀黍和小萝莉不得不说的故事。
千与千寻:最好的宫崎骏,最好的久石让。
美丽人生:最美的谎言。
辛德勒的名单:拯救一个人,就是拯救整个世界。
星际穿越:爱是一种力量,让我们超越时空感知它的存在。
、、、
、、、
、、、【不予展开了】
也可以通过命令行,保存成json格式。
平时可以不通过命令行运行 scrapy
只需要在最外围定义【run.py】
# -*- coding: utf-8 -*-
from scrapy.cmdline import execute
execute(['scrapy', 'crawl', 'douban'])
运行此函数能直接是爬虫跑起来
保存json格式时
定义【save.py】
# -*- coding: utf-8 -*-
from scrapy.cmdline import execute
execute(['scrapy', 'crawl', 'douban','-o', 'items.json','-t','json'])
以上两个模块的【douban】、【items】.json根据自己需要修改
[scrapy]一个简单的scrapy爬虫demo的更多相关文章
- 做一个简单的scrapy爬虫
前言: 做一个简单的scrapy爬虫,带大家认识一下创建scrapy的大致流程.我们就抓取扇贝上的单词书,python的高频词汇. 步骤: 一,新建一个工程scrapy_shanbay 二,在工程中中 ...
- 一个简单的webservice的demo(下)winform异步调用webservice
绕了一大圈,又开始接触winform的项目来了,虽然很小吧.写一个winform的异步调用webservice的demo,还是简单的. 一个简单的Webservice的demo,简单模拟服务 一个简单 ...
- 一个简单的Webservice的demo(中)_前端页面调用
首先新建项目,这里有两种调用方式,为了能方便理解,新建页面WebserviceTest如下图: 先引用写好的服务,这里用上次写好的服务.见上次写的一个简单的Webservice的demo,简单模拟服务 ...
- 一个简单的python爬虫程序
python|网络爬虫 概述 这是一个简单的python爬虫程序,仅用作技术学习与交流,主要是通过一个简单的实际案例来对网络爬虫有个基础的认识. 什么是网络爬虫 简单的讲,网络爬虫就是模拟人访问web ...
- python实现的一个简单的网页爬虫
学习了下python,看了一个简单的网页爬虫:http://www.cnblogs.com/fnng/p/3576154.html 自己实现了一个简单的网页爬虫,获取豆瓣的最新电影信息. 爬虫主要是获 ...
- Java实现一个简单的网络爬虫
Java实现一个简单的网络爬虫 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWri ...
- 一个简单的C#爬虫程序
这篇这篇文章主要是展示了一个C#语言如何抓取网站中的图片.实现原理就是基于http请求.C#给我们提供了HttpWebRequest和WebClient两个对象,方便发送请求获取数据,下面看如何实 1 ...
- 一个简单的python爬虫,爬取知乎
一个简单的python爬虫,爬取知乎 主要实现 爬取一个收藏夹 里 所有问题答案下的 图片 文字信息暂未收录,可自行实现,比图片更简单 具体代码里有详细注释,请自行阅读 项目源码: # -*- cod ...
- 一个简单的scrapy爬虫抓取豆瓣刘亦菲的图片地址
一.第一步是创建一个scrapy项目 sh-3.2# scrapy startproject liuyifeiImage sh-3.2# chmod -R 777 liuyifeiImage/ 二.分 ...
- 一个简单的Webservice的demo,简单模拟服务
前段时间一直在学习WCF,匆匆忙忙的把<WCF全面解析>和<WCF服务编程>看了一遍,好多东西都不是很懂,又听了一下WCF分布式开发的网络教程,算是马马虎虎的明白点了.回顾了一 ...
随机推荐
- EXP 一款 Java 插件化热插拔框架
EXP 一款 Java 插件化热插拔框架 前言 多年以来,ToB 的应用程序都面临定制化需求应该怎么搞的问题. 举例,大部分本地化软件厂家,都有一个标准程序,这个程序支持大部分企业的功能需求,但面对世 ...
- 论文解读(CBL)《CNN-Based Broad Learning for Cross-Domain Emotion Classification》
Note:[ wechat:Y466551 | 付费咨询,非诚勿扰 ] 论文信息 论文标题:CNN-Based Broad Learning for Cross-Domain Emotion Clas ...
- 【pandas小技巧】--category类型补充
category类型在pandas基础系列中有一篇介绍数据类型的文章中已经介绍过.category类型并不是python中的类型,是pandas特有的类型. category类型的优势那篇文章已经介绍 ...
- 十年磨一剑的华为云GES,高明在哪
本文分享自华为云社区<华为云GES:十年磨一剑,打造业界一流的云原生分布式图数据库>,作者:GES图引擎服务小图 . 1.浅谈云原生图数据库 图数据库(graph database)是一个 ...
- 快手商品详情API接口如何使用
使用快手开的API接口获取商品详情,可按照以下步骤进行: 1.注册账号并创建应用 注册开发者账号,并在账号后台中创建一个应用,获得AppKey和AppSecret等信息.这些信息是使用API接口访问快 ...
- xlsx和path的运用
从后端获取Excel模板 app.get('/api/download-template', (req, res) => { const templatePath = path.join(__d ...
- [WPF]使用HLSL实现百叶窗动效
百叶窗动画是制作PPT时常用的动画之一,本文将通过实现百叶窗动画效果的例子介绍在WPF中如何使用ShaderEffect.ShaderEffect是使用高级着色器语言(High Level Shadi ...
- 一文搞懂 OTP 双因素认证
GitHub 在 2023 年 3 月推出了双因素认证(two-factor authentication)简称 2FA,并且承诺所有在 GitHub 上贡献的开发者在 2023 年底前启用双因素认证 ...
- CocoaPods 在iOS开发中养活了这么多项目,它到底是个啥?
对于iOS开发者而言,CocoaPods并不陌生,通过pod相关的命令操作,就可以很方便的将项目中用到的三方依赖库资源集成到项目环境中,大大的提升了开发的效率.CocoaPods作为iOS项目的包管理 ...
- Redis最常见的5种应用场景
Redis作为当今最流行的内存数据库,已经成为服务端加速的必备工具之一.对于Redis为什么那么快?以及Redis采用单线程,但为什么反而获得更高的性能的疑问,在之前的Redis为什么那么快?一文中, ...