<scrapy爬虫>爬取quotes.toscrape.com
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的更多相关文章
- 使用scrapy爬虫,爬取17k小说网的案例-方法一
无意间看到17小说网里面有一些小说小故事,于是决定用爬虫爬取下来自己看着玩,下图这个页面就是要爬取的来源. a 这个页面一共有125个标题,每个标题里面对应一个内容,如下图所示 下面直接看最核心spi ...
- <scrapy爬虫>爬取360妹子图存入mysql(mongoDB还没学会,学会后加上去)
1.创建scrapy项目 dos窗口输入: scrapy startproject images360 cd images360 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) ...
- 使用scrapy爬虫,爬取今日头条搜索吉林疫苗新闻(scrapy+selenium+PhantomJS)
这一阵子吉林疫苗案,备受大家关注,索性使用爬虫来爬取今日头条搜索吉林疫苗的新闻 依然使用三件套(scrapy+selenium+PhantomJS)来爬取新闻 以下是搜索页面,得到吉林疫苗的搜索信息, ...
- <scrapy爬虫>爬取猫眼电影top100详细信息
1.创建scrapy项目 dos窗口输入: scrapy startproject maoyan cd maoyan 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) # -*- ...
- <scrapy爬虫>爬取校花信息及图片
1.创建scrapy项目 dos窗口输入: scrapy startproject xiaohuar cd xiaohuar 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) # ...
- <scrapy爬虫>爬取腾讯社招信息
1.创建scrapy项目 dos窗口输入: scrapy startproject tencent cd tencent 2.编写item.py文件(相当于编写模板,需要爬取的数据在这里定义) # - ...
- scrapy爬虫爬取小姐姐图片(不羞涩)
这个爬虫主要学习scrapy的item Pipeline 是时候搬出这张图了: 当我们要使用item Pipeline的时候,要现在settings里面取消这几行的注释 我们可以自定义Item Pip ...
- 使用scrapy爬虫,爬取今日头条首页推荐新闻(scrapy+selenium+PhantomJS)
爬取今日头条https://www.toutiao.com/首页推荐的新闻,打开网址得到如下界面 查看源代码你会发现 全是js代码,说明今日头条的内容是通过js动态生成的. 用火狐浏览器F12查看得知 ...
- 使用scrapy爬虫,爬取起点小说网的案例
爬取的页面为https://book.qidian.com/info/1010734492#Catalog 爬取的小说为凡人修仙之仙界篇,这边小说很不错. 正文的章节如下图所示 其中下面的章节为加密部 ...
随机推荐
- re.match与re.search的区别
re.match与re.search的区别 re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None:而re.search匹配整个字符串,直到找到一个匹配. 实 ...
- Java——方法的重写(覆盖)
2.2方法的重写(覆盖)(override,orverwrite) 2.2.1 什么时候方法要进行重写? 如果父类中的方法已经无法满足当前子类的业务需求,需要将父类中的方法进行重新写一遍.就是要改变父 ...
- 43 编译原理及cmake使用手册学习
0 引言 大量开源库需要通过cmake编译后使用,了解cmake的基本指令以及CMakeLists.txt的写法非常重要,其基础是了解编译原理.另外,为了对cmake编译的代码进行调试,需要了解CMa ...
- IDEA maven package失败
选中要打包的模块,选择工具栏中的Build,选择Rebuild Module xxx,重新打包
- 2018-2019-2-20175323 java实验二《Java面向对象程序设计》
单元测试 1.在IDEA中新建项目并输入单元测试的代码 2.在IDEA中下载Junit,我发现Junit已经存在了 3.新建test文件 遇到的问题 发现Junit红字解析不了 解决办法:查找到jun ...
- 2019 牛客多校第三场 B Crazy Binary String
题目链接:https://ac.nowcoder.com/acm/contest/883/B 题目大意 给定一个长度为 N 的 01 字符串,输出最长子串和子序列的长度,满足其中 0 和 1 的个 ...
- sails中创建和使用services
从sails官方在线文档查知 // EmailService.js - in api/services module.exports = { sendInviteEmail: function(opt ...
- abstract类中method
一.abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized? 都不可以,因为abstract申明的方法是要求子类去实现的,abstrac ...
- iOS开发系列-打印内存地址
打印内存地址 基本数据类型 定义一个基本数据类型,会根据变量类型分配对应的内存空间.比如定义一个int类型的变量a. int a = 10; 内存如下 输入变量a在内存中内存地址 NSLog(@&qu ...
- Linux 服务器 个人常用操作命令记录
1.实时查看log:tail -f 日志文件名 2.查看Apache运行的用户组或用户名:ps aux | grep httpd 或者是: ps -ef | grep httpd 3.查看cronta ...