爬虫系列----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中. 最后尝试对爬取到的数据做一个简单的分析. 克服 ...
随机推荐
- 《HelloGitHub月刊》第 05 期
<HelloGitHub>第 05 期 兴趣是最好的老师,<HelloGitHub>就是帮你找到兴趣! 欢迎各路人士加入本项目,丰富月刊的内容,也可以直接在Issue(需要登录 ...
- [工具向]__关于androidstudio工具使用过程中学习到的一些知识点简记
前言 在我学习android开发课程的过程中,我们通常只会关注编程语言上面的一些知识点与问题,而忽略了开发工具的使用上的一些遇到的一些知识,其实每一款IDE工具都是集编程语言大成而开发出来的,其中有很 ...
- import 和 export
1.export 命令 export 命令用于规定模块的对外接口. 一个模块就是一个独立的文件.该文件内部所有的变量,外部无法获取.要想外部能够读取模块内部的某个变量,就必须使用 export 关键字 ...
- leetcode — gray-code
import org.lep.leetcode.groupanagrams.GroupAnagram; import java.util.ArrayList; import java.util.Arr ...
- Data Source与数据库连接池简介 JDBC简介(八)
DataSource是作为DriverManager的替代品而推出的,DataSource 对象是获取连接的首选方法. 起源 为何放弃DriverManager DriverManager负责管理驱动 ...
- 不要使用Resource Owner Password Credentials
不要使用Resource Owner Password Credentials 文章链接在这里 前言 最近公司项目在做一些重构,因为公司多个业务系统各自实现了一套登录逻辑,比较混乱.所以,现在需要做一 ...
- 巨杉数据库入选Gartner数据库报告,中国首家入选厂商
SequoiaDB巨杉数据库入选Gartner数据库报告,成为国内首批入选Gartner报告的数据库厂商. “SequoiaDB, 总部位于中国广州,是一款分布式.多模型(Multimodel).高可 ...
- Smobiler 4.4 更新预告 Part 2(Smobiler能让你在Visual Studio上开发APP)
Hello Everybody,在Smobiler 4.4中,也为大家带来了新增功能和插件(重点,敲黑板). 新增功能: 1, 企业认证用户可设置路由(即客户端可根据不同的IP地址访问不同的服务器组) ...
- 别的C#基础笔记
1.方法名称 * 规范:每一个单词的首字母大写 2.方法的返回值 * void:没有返回值.不能使用return来返回具体的值 ,但是可以使用return终止当前方法 ...
- VSTO中Word的Range复制方式
VSTO中Word的Range复制方式 前言 VSTO是一套用于创建自定义Office应用程序的Visual Studio工具包,通过Interop提供的增强Office对象,可以对Word文档进行编 ...