爬虫系列----scrapy爬取网页初始
一 基本流程
- 创建工程,工程名称为(cmd):firstblood: scrapy startproject firstblood
- 进入工程目录中(cmd):cd :./firstblood
- 创建爬虫文件(cmd):scrapy genspider first www.xxx.con (first为爬虫文件名称 www.xxx.com :起始url)
- pycharm打开爬虫项目,进入到spider文件下,找到first爬虫文件,书写爬虫代码.注释allowed_domains
- 启动爬虫文件(cmd):scrapy crawl first
***在pycharm中启动设置方法
#在项目根目录下新建:entrypoint.py
from scrapy.cmdline import execute
execute(['scrapy', 'crawl', '爬虫名称'])
二 spider反反爬配置
- robot.txt
settings 中修改为:ROBOTSTXT_OBEY = False
- UA伪装
setting文件中
USER_AGENT = 'firstblood (+http://www.yourdomain.com)'
修改为:
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' 自定义请求头信息,重写start_requests方法:
def start_requests(self):
headers={
'Host': 'www.amazon.cn',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36', }
url='https://www.amazon.cn/s/ref=nb_sb_noss?__mk_zh_CN=%E4%BA%9A%E9%A9%AC%E9%80%8A%E7%BD%91%E7%AB%99&url=search-alias%3Daps&field-keywords=iphone-x'
resquest=scrapy.Request(url=url,headers=headers)
yield resquest
三 基本命令汇总
- scrapy startproject firstblood #新建工程
- scrapy genspider first www.xxx.con #新建爬虫文件
- scrapy crawl first #执行爬虫文件,并打印日记
- scrapy crawl first --nolog #执行爬虫文件,不打印日记
- scrapy crawl qiubai -o qiushibaike.csv 把parse函数的返回结果存入csv文件中
- scrapy genspider -t crawl chouti www.xxx.com 创建crawspider爬虫项目
四 存储
基于终端指令的持久化存储(只会将parse函数返回值进行本地持久化存储)
命令: scrapy crawl qiubai -o qiushibaike.csv
局限性:只能存储这些后缀的文件('json', 'jsonlines', 'jl', 'csv', 'xml', 'marshal', 'pickle')
class QiubaiSpider(scrapy.Spider):
name = 'qiubai'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response):
div_list=response.xpath("//div[@id='content-left']/div")
res_list=[]
for div in div_list:
# author=div.xpath('./div[1]/a[2]/h2/text()')[0]
##scrapy中的xpath返回的是select对象
#<Selector xpath='./div[1]/a[2]/h2/text()' data='\n胡子灬哥\n'>
#获取select对象中data的数据 # 方式一:author=div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
# 方式二:author=div.xpath('./div[1]/a[2]/h2/text()').extract_first()
author=div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
content=div.xpath('./a[1]/div[@class="content"]/span//text()').extract()
content="".join(content) # print("author......",author)
# print("content......",content)
# break
dic={
'author':author,
'content':content
}
res_list.append(dic)
return res_list
基于管道操作的持久化存储(持久化存储的操作必须写在管道文件中)
推荐使用:
pip install redis==2.10.6
如何把数据封装到item对象中
1.在items.py文件中定义存储字段的属性
class QiubaiproItem(scrapy.Item):
# define the fields for your item here like:(定义字段如下:)
# name = scrapy.Field() (name字段=scrapy万能字段)
#示例
author=scrapy.Field()
content=scrapy.Field()
2.爬虫文件spiders/qiubai.py中引入定义的item类:
from qiubaiPro.items import QiubaiproIte
3.实例化items对象
#实例化 item对象
item=QiubaiproItem()
item['author']=author
item['content']=content
#注意:一条数据一个item对象,pipeline接受一个item就存储一条记录
4.把实例化的对象提交给管道,scrapy自动提交,我们只需要写:
yield item #每条数据提交一次
5.pipeline.py文件中书写管道存储的逻辑(三种存储方式)
class QiubaiproPipeline(object):
def process_item(self, item, spider):
print(item)
return item
import pymysql
class Mysql_PipeLine(object):
#全局定义管道conn和游标cursor
#导入pymysql
conn=None
cursor=None
def open_spider(self, spider):
#端口号是数字而非字符串,
self.conn=pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='',db='scrapy')
self.cursor = self.conn.cursor()
def process_item(self, item, spider):
# print(item)
try:
self.cursor.execute('insert into qiubai values ("%s","%s");'%(item['author'],item['content']))
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback()
return item def close_spider(self, spider):
# self.cursor.close()
self.conn.close() from redis import Redis
class Redis_PipeLine(object):
conn=None def open_spider(self,spider):
# 链接数据库
self.conn=Redis(host='127.0.0.1',port=6379) def process_item(self,item,spider):
dic={
'author':item['author'],
'content':item['content']
}
self.conn.lpush('qiubai',dic) 6 settings文件中开启item_pipeline功能
#允许书写多个管道,多种存储方式
ITEM_PIPELINES = {
'qiubaiPro.pipelines.QiubaiproPipeline': 300,
#'管道路径.管道名称':优先级
} ITEM_PIPELINES = {
'qiubaiPro.pipelines.QiubaiproPipeline': 300,
#新增的管道
'qiubaiPro.pipelines.Mysql_PipeLine': 301,
'qiubaiPro.pipelines.Redis_PipeLine': 302, }
五 简单实例
- 新建的爬虫文件qiubai.py
# -*- coding: utf-8 -*-
import scrapy
from qiubaiPro.items import QiubaiproItem '''
1 基于终端指令的持久化存储(只会将parse函数返回值进行本地持久化存储)
命令: scrapy crawl qiubai -o qiushibaike.csv 局限性:只能存储这些后缀的文件('json', 'jsonlines', 'jl', 'csv', 'xml', 'marshal', 'pickle')
'''
# 基于终端指令的持久化存储(只会将parse函数返回值进行本地持久化存储)
class QiubaiSpider(scrapy.Spider):
name = 'qiubai'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response):
div_list=response.xpath("//div[@id='content-left']/div")
res_list=[]
for div in div_list: author=div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
content=div.xpath('./a[1]/div[@class="content"]/span//text()').extract()
content="".join(content) dic={
'author':author,
'content':content
}
res_list.append(dic)
return res_list # 基于管道操作的持久化存储(持久化存储的操作必须写在管道文件中)
class QiubaiSpider(scrapy.Spider):
name = 'qiubai'
start_urls = ['https://www.qiushibaike.com/text/'] def parse(self, response):
div_list=response.xpath("//div[@id='content-left']/div")
for div in div_list:
try:
author=div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
except Exception as e:
# print(e)
author=div.xpath('./div[1]/span[2]/h2/text()')[0].extract() content=div.xpath('./a[1]/div[@class="content"]/span//text()').extract()
content="".join(content) #实例化 item对象
item=QiubaiproItem()
item['author']=author
item['content']=content
# print(item['author'])
#提交管道
yield item
- items.py
import scrapy
class QiubaiproItem(scrapy.Item):
author=scrapy.Field()
content=scrapy.Field()
- pipeline.py
# -*- coding: utf-8 -*-
import pymysql
from redis import Redis #一个类对应一个存储方式
#存入文件qiubai.txt
class QiubaiproPipeline(object):
fp = None # 文件管道 # open_spider重写父类方法,爬虫过程中只会执行一次
def open_spider(self,spider):
self.fp=open('qiubai.txt','w',encoding='utf-8') # 处理item文件会执行多次,因此文件打开和关闭操作不应该放在这个函数内部,
# 否则,执行效率太低
def process_item(self, item, spider):
# print(item)
self.fp.write(item['author']+':'+item['content'])
return item # close_spider重写父类spider的方法,在爬虫执行过程只会执行一次 def close_spider(self,spider):
self.fp.close() #存入mysql数据库
#同时在settings添加该管道路径
class Mysql_PipeLine(object):
#全局定义管道conn和游标cursor
#导入pymysql
conn=None
cursor=None
def open_spider(self, spider):
#端口号是数字而非字符串,
self.conn=pymysql.Connect(host='127.0.0.1',port=3306,user='root',password='',db='scrapy')
self.cursor = self.conn.cursor()
def process_item(self, item, spider):
# print(item)
try:
self.cursor.execute('insert into qiubai values ("%s","%s");'%(item['author'],item['content']))
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback()
return item def close_spider(self, spider):
# self.cursor.close()
self.conn.close() class Redis_PipeLine(object):
conn=None def open_spider(self,spider):
# 链接数据库
self.conn=Redis(host='127.0.0.1',port=6379) def process_item(self,item,spider):
dic={
'author':item['author'],
'content':item['content']
}
self.conn.lpush('qiubai',dic)
六 scrapy中的xpath的不同点
- scrapy中xpath表达式获取到的数据不是标签对象,而是select对象
author=div.xpath('./div[1]/a[2]/h2/text()')[0]
#<Selector xpath='./div[1]/a[2]/h2/text()' data='\n胡子灬哥\n'>
- 获取select对象中的data的数据
方式一:author=div.xpath('./div[1]/a[2]/h2/text()')[0].extract()
方式二:author=div.xpath('./div[1]/a[2]/h2/text()').extract_first()
author=div.xpath('./div[1]/a[2]/h2/text()')[0].extract() #返回值为列表
七 日记处理
爬虫系列----scrapy爬取网页初始的更多相关文章
- 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...
- 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...
- 爬虫实战——Scrapy爬取伯乐在线所有文章
Scrapy简单介绍及爬取伯乐在线所有文章 一.简说安装相关环境及依赖包 1.安装Python(2或3都行,我这里用的是3) 2.虚拟环境搭建: 依赖包:virtualenv,virtualenvwr ...
- 小说免费看!python爬虫框架scrapy 爬取纵横网
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 风,又奈何 PS:如有需要Python学习资料的小伙伴可以加点击下方 ...
- scrapy爬虫系列之四--爬取列表和详情
功能点:如何爬取列表页,并根据列表页获取详情页信息? 爬取网站:东莞阳光政务网 完整代码:https://files.cnblogs.com/files/bookwed/yangguang.zip 主 ...
- 网络爬虫之scrapy爬取某招聘网手机APP发布信息
1 引言 过段时间要开始找新工作了,爬取一些岗位信息来分析一下吧.目前主流的招聘网站包括前程无忧.智联.BOSS直聘.拉勾等等.有段时间时间没爬取手机APP了,这次写一个爬虫爬取前程无忧手机APP岗位 ...
- 精通python网络爬虫之自动爬取网页的爬虫 代码记录
items的编写 # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentati ...
- Python爬虫系列之爬取美团美食板块商家数据(二)
今天为大家重写一个美团美食板块小爬虫,说不定哪天做旅游攻略的时候也可以用下呢.废话不多说,让我们愉快地开始吧~ 开发工具 Python版本:3.6.4 相关模块: requests模块: argpar ...
- Python爬虫系列之爬取美团美食板块商家数据(一)
主要思路 目的: 根据输入的城市名,爬取该城市美团美食板块所有商家的数据.数据包括: 店名.评分.评论数量.均价.地址, 并将这些数据存入Excel中. 最后尝试对爬取到的数据做一个简单的分析. 克服 ...
随机推荐
- 规避 React 组件中的 bind(this)
React 组件中处理 onClick 类似事件绑定的时候,是需要显式给处理器绑定上下文(context)的,这一度使代码变得冗余和难看. 请看如下的示例: class App extends Com ...
- oracle数据库之plsql可视化操作建表
首先登录PL/SQL developer. 点击工具栏中的第一个图标,选择“表”. 右边会弹出一个窗口,我们以可视化方式来创建一个Table. 如下图所示,在“一般”选项卡中,输入“名称” ...
- maven-代码风格检查工具
目录 checkstyle findbugs pmd 其他 checkstyle checkstyle 用于对代码风格进行检查 checkstyle-maven插件 操作示例 mvn clean co ...
- man帮助文档打印
这里不讨论大家都知道的man重定向的一般常用方法(col处理方法)$ man find | col -b > man_fine.txt [跟着我的思路走]假如您像我一样,直接使用如下命令导出fi ...
- Linux基础知识第八讲,系统相关操作命令
目录 Linux基础知识第八讲,系统相关操作命令 一丶简介命令 2.磁盘信息查看. 3.系统进程 Linux基础知识第八讲,系统相关操作命令 一丶简介命令 时间和日期 date cal 磁盘和目录空间 ...
- 【面试】我是如何面试别人List相关知识的,深度有点长文
- 系统开发中使用拦截器校验是否登录并使用MD5对用户登录密码进行加密
项目名称:客户管理系统 项目描述: 项目基于javaEE平台,B/S模式开发.使用Struts2.Hibernate/Spring进行项目框架搭建.使用Struts中的Action 控制器进行用户访问 ...
- Docker系列06—基于容器制作镜像并上传到Docker Registry
本文收录在容器技术学习系列文章总目录 1.制作镜像 1.1 镜像的生成途径 基于容器制作 dockerfile,docker build 本篇主要详细讲解基于容器制作镜像:基于dockerfile 制 ...
- Mysql加锁过程详解(8)-理解innodb的锁(record,gap,Next-Key lock)
Mysql加锁过程详解(1)-基本知识 Mysql加锁过程详解(2)-关于mysql 幻读理解 Mysql加锁过程详解(3)-关于mysql 幻读理解 Mysql加锁过程详解(4)-select fo ...
- Spring Cloud Alibaba基础教程:Nacos配置的多环境管理
前情回顾: <Spring Cloud Alibaba基础教程:使用Nacos实现服务注册与发现> <Spring Cloud Alibaba基础教程:支持的几种服务消费方式> ...