1.创建scrapy项目

dos窗口输入:

scrapy startproject quote
cd quote

2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义)

import scrapy

class QuoteItem(scrapy.Item):
# define the fields for your item here like:
text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()

  

3.创建爬虫文件

dos窗口输入:

scrapy genspider myspider quotes.toscrape.com

4.编写myspider.py文件(接收响应,处理数据)

# -*- coding: utf-8 -*-
import scrapy
from quote.items import QuoteItem class MyspiderSpider(scrapy.Spider):
name = 'myspider'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/'] def parse(self, response):
for each in response.xpath('//div[@class="quote"]'):
item = QuoteItem()
item['text'] = each.xpath('./span/text()').extract()[0]
item['author'] = each.xpath('.//small/text()').extract()[0]
list = each.xpath('.//a[@class="tag"]/text()').extract()
#列表形式的文件不能存入mysql,需要弄成str形式
item['tags']= '/'.join(list)
yield item next = response.xpath('//li[@class="next"]/a/@href').extract()[0]
url = response.urljoin(next)
yield scrapy.Request(url=url,callback=self.parse)

  

5.编写pipelines.py(存储数据)

存储到mysql

import pymysql.cursors

class QuotePipeline(object):
def __init__(self):
self.connect = pymysql.connect(
host='localhost',
user='root',
password='',
database='quotes',
charset='utf8',
)
self.cursor = self.connect.cursor() def process_item(self, item, spider):
item = dict(item)
sql = 'insert into quote(text,author,tags) values(%s,%s,%s)'
self.cursor.execute(sql,(item['text'],item['author'],item['tags']))
self.connect.commit()
return item def close_spider(self,spider):
self.cursor.close()
self.connect.close()  

改进版:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql.cursors class QuotePipeline(object):
def __init__(self):
self.connect = pymysql.connect(
host='localhost',
user='root',
password='',
database='quotes',
charset='utf8',
)
self.cursor = self.connect.cursor() def process_item(self, item, spider):
item = dict(item)
table = 'quote'
keys = ','.join(item.keys())
values = ','.join(['%s']*len(item))
sql = 'insert into {table}({keys}) values({values})'.format(table=table,keys=keys,values=values)
try:
if self.cursor.execute(sql, tuple(item.values())):
self.connect.commit()
print("Successful!")
except:
print("Failed!")
self.connect.rollback()
return item def close_spider(self, spider):
self.cursor.close()
self.connect.close()

存储到mongoDB

  1.在setting文件设置2个属性

MONGO_URI = 'localhost'
MONGO_DB = 'study' #一个管道文件 ITEM_PIPELINES = {
# 'quote.pipelines.QuotePipeline': 300,
'quote.pipelines.MongoPipeline': 300, }

  2.pipeline.py

import pymongo

class MongoPipeline(object):
# 表名字
collection = 'student' def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db @classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DB'),
) def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db] def close_spider(self, spider):
self.client.close() def process_item(self, item, spider):
# 插入到mongo数据库
self.db[self.collection].insert(dict(item))
return item

  

    

6.编写settings.py(设置headers,pipelines等)

robox协议

# Obey robots.txt rules
ROBOTSTXT_OBEY = False  

headers

DEFAULT_REQUEST_HEADERS = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
}

pipelines

ITEM_PIPELINES = {
'quote.pipelines.QuotePipeline': 300,
}

  

7.运行爬虫

dos窗口输入:

scrapy crawl myspider 

运行结果

<scrapy爬虫>爬取quotes.toscrape.com的更多相关文章

  1. 使用scrapy爬虫,爬取17k小说网的案例-方法一

    无意间看到17小说网里面有一些小说小故事,于是决定用爬虫爬取下来自己看着玩,下图这个页面就是要爬取的来源. a 这个页面一共有125个标题,每个标题里面对应一个内容,如下图所示 下面直接看最核心spi ...

  2. <scrapy爬虫>爬取360妹子图存入mysql(mongoDB还没学会,学会后加上去)

    1.创建scrapy项目 dos窗口输入: scrapy startproject images360 cd images360 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) ...

  3. 使用scrapy爬虫,爬取今日头条搜索吉林疫苗新闻(scrapy+selenium+PhantomJS)

    这一阵子吉林疫苗案,备受大家关注,索性使用爬虫来爬取今日头条搜索吉林疫苗的新闻 依然使用三件套(scrapy+selenium+PhantomJS)来爬取新闻 以下是搜索页面,得到吉林疫苗的搜索信息, ...

  4. <scrapy爬虫>爬取猫眼电影top100详细信息

    1.创建scrapy项目 dos窗口输入: scrapy startproject maoyan cd maoyan 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) # -*- ...

  5. <scrapy爬虫>爬取校花信息及图片

    1.创建scrapy项目 dos窗口输入: scrapy startproject xiaohuar cd xiaohuar 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) # ...

  6. <scrapy爬虫>爬取腾讯社招信息

    1.创建scrapy项目 dos窗口输入: scrapy startproject tencent cd tencent 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) # - ...

  7. scrapy爬虫爬取小姐姐图片(不羞涩)

    这个爬虫主要学习scrapy的item Pipeline 是时候搬出这张图了: 当我们要使用item Pipeline的时候,要现在settings里面取消这几行的注释 我们可以自定义Item Pip ...

  8. 使用scrapy爬虫,爬取今日头条首页推荐新闻(scrapy+selenium+PhantomJS)

    爬取今日头条https://www.toutiao.com/首页推荐的新闻,打开网址得到如下界面 查看源代码你会发现 全是js代码,说明今日头条的内容是通过js动态生成的. 用火狐浏览器F12查看得知 ...

  9. 使用scrapy爬虫,爬取起点小说网的案例

    爬取的页面为https://book.qidian.com/info/1010734492#Catalog 爬取的小说为凡人修仙之仙界篇,这边小说很不错. 正文的章节如下图所示 其中下面的章节为加密部 ...

随机推荐

  1. Python 列表,元组,字典

    0)字符串切片 py_str = 'python' >>>py_str[0] #取第一个字符串,返回值为"p",超出范围会报错 >>>py_st ...

  2. AdaBoost笔记之通俗易懂原理介绍

    转自:https://blog.csdn.net/px_528/article/details/72963977 写在前面 说到Adaboost,公式与代码网上到处都有,<统计学习方法>里 ...

  3. vs2013代码高亮显示失效

    问题: 最近使用vs2013写代码的时候经常遇到一种问题,当我们的工程逐渐变大时,突然有一个文件出现以上问题,这并不是设置提示的问题,因为当你打开别的工程时该问题不会出现.这其实是配置缓存的问题,而V ...

  4. 如何再windows里面装Tableau Server

    1.进入网页http://www.tableau.com/support/esdalt下载所需要的软件. 我的是正版下载的是 2.点击tableauServer-64bit-10....这个软件 一直 ...

  5. NetBeans简介和简单使用

    1.什么是NetBeans? NetBeans IDE:可以使开发人员利用Java平台能够快速创建Web.企业.桌面以及移动的应用程序: 支持语言:PHP.Ruby.JavaScript.Groovy ...

  6. 实战CGLib系列之proxy篇(一):方法拦截MethodInterceptor

    实战CGLib系列文章 本篇介绍通过MethodInterceptor和Enhancer实现一个动态代理. 一.首先说一下JDK中的动态代理: JDK中的动态代理是通过反射类Proxy以及Invoca ...

  7. Flink 1.6.0 Windows操作

    原文连接 https://ci.apache.org/projects/flink/flink-docs-release-1.6/dev/stream/operators/windows.html W ...

  8. 14-Ubuntu-文件和目录命令-查看目录内容-ls-1

    1.终端使用技巧 (1)tab键自动补全 (2)按上/下光标键查看使用过的命令 (3)退出当前命令,Ctrl C (4)缩小--Ctrl - ;放大--Ctrl shift + 2.ls 命令--查看 ...

  9. 2- SQL语句的强化

    查询类型cate_name为 '超极本' 的商品名称.价格 select name,price from goods where cate_name = '超级本'; 显示商品的种类 select c ...

  10. 面试系列38 分库分表之后,id主键如何处理?

    (1)数据库自增id 这个就是说你的系统里每次得到一个id,都是往一个库的一个表里插入一条没什么业务含义的数据,然后获取一个数据库自增的一个id.拿到这个id之后再往对应的分库分表里去写入. 这个方案 ...