<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 爬取的小说为凡人修仙之仙界篇,这边小说很不错. 正文的章节如下图所示 其中下面的章节为加密部 ...
随机推荐
- 廖雪峰Java13网络编程-1Socket编程-2TCP编程
1. Socket 在开发网络应用程序的时候,会遇到Socket这个概念. Socket是一个抽象概念,一个应用程序通过一个Socket来建立一个远程连接,而Socket内部通过TCP/IP协议把数据 ...
- delphi 获取所有窗口标题
unit Unit1; interface usesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ...
- Delphi GDI对象之脱屏位图(Offscreen Bitmaps)
脱屏位图(Offscreen Bitmaps) 脱屏位图,也叫内存位图,普遍用于Windows程序设计中.它在内存中制作图像,然后利用Draw方法在屏幕上显示出来.当用户想更快的在屏幕上绘制图像时,脱 ...
- CommandLineToArgvW调EXE传入参数【转载】
#include <afxwin.h> // TODO: add your code here LPWSTR *szArglist = NULL; ; szArglist = Comma ...
- (转)HashSet<T>类
转载于:http://www.importnew.com/6931.html HashSet<T>类主要是设计用来做高性能集运算的,例如对两个集合求交集.并集.差集等.集合中包含一组不重复 ...
- 反射Reflection
using System; using System.Collections.Generic; using System.Linq; using System.Reflection;// <-- ...
- DRF的三大认证组件
目录 DRF的三大认证组件 认证组件 工作原理 实现 权限组件 工作原理 实现 频率组件 工作原理 实现 三种组件的配置 DRF的三大认证组件 认证组件 工作原理 首先,认证组件是基于BaseAuth ...
- Lunascape:将FireFox、Safari和IE合为一体的浏览器
转自:http://blog.bingo929.com/lunascape-firefox-safari-ie-all-in-one.html 作为前端开发/网页设计师,电脑中总是安装着各种不同内核渲 ...
- 使用CSS3开启GPU硬件加速提升网站动画渲染性能
遇到的问题: 网站本身设计初衷就没有打算支持IE8及以下版本浏览器,并不是因为代码兼容性问题,而是真的不想迁就那些懒得更新自己操作系统和浏览器的用户,毕竟是我自己的网站,所以我说了算!哈哈~ 没有了低 ...
- MySQL 11章_索引、触发器
一. 索引: . 为什么要使用索引: 一本书需要目录能快速定位到寻找的内容,同理,数据表中的数据很多时候也可以为他们创建相应的“目录”,称为索引,当创建索引后查询数据也会更加高效 . Mysql中的索 ...