爬虫系列----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中. 最后尝试对爬取到的数据做一个简单的分析. 克服 ...
随机推荐
- ASP.NET在MVC控制器中获取Form表单值的方法
在网站开发中我们经常需要用到表单,那么,在前台页面的表单中提交到后台控制器后,后台控制器如何接收表单提交过来的数据呢?下面我们介绍几种常用的方法. 我们先看看前台页面,这里我们用一个用户名和密码的表单 ...
- Java基础17:Java IO流总结
更多内容请关注微信公众号[Java技术江湖] 这是一位阿里 Java 工程师的技术小站,作者黄小斜,专注 Java 相关技术:SSM.SpringBoot.MySQL.分布式.中间件.集群.Linux ...
- Chapter 5 Blood Type——9
He grimaced. 他扮了一个鬼脸. "Or better," I continued, the pent-up annoyance flowing freely now, ...
- leetcode — decode-ways
/** * Source : https://oj.leetcode.com/problems/decode-ways/ * * * A message containing letters from ...
- JDBC事务与保存点 JDBC简介(七)
事务简介 数据库事务(Database Transaction) ,是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行. 事务是必须满足4个条件(ACID) 事务的原子性( A ...
- [二十一]JavaIO之BufferedReader 与 BufferedWriter
功能简介 BufferedReader 从字符输入流中读取文本,内部缓冲各个字符,从而实现字符.数组和行的高效读取 BufferedWriter 将文本写入字符输出流,内部缓冲各个字符,从而提供单个 ...
- SpringCloud系列——Zuul 动态路由
前言 Zuul 是在Spring Cloud Netflix平台上提供动态路由,监控,弹性,安全等边缘服务的框架,是Netflix基于jvm的路由器和服务器端负载均衡器,相当于是设备和 Netflix ...
- 第10章 使用密码保护API - Identity Server 4 中文文档(v1.0.0)
OAuth 2.0资源所有者密码授权允许客户端向令牌服务发送用户名和密码,并获取代表该用户的访问令牌. 除了无法承载浏览器的旧应用程序之外,规范通常建议不要使用资源所有者密码授予.一般来说,当您要对用 ...
- eclipse中的出现在打包一次后,后面新建的项目都出错了,出现support_v7下面出现红线及解决方法及为什么eclipse中项目继承ActionBarActivity解决方法一样
第一次写博客,有什么问题或者想法的希望各位可以进行评论交流,望大家多多包涵! 遇到的问题是在新建的项目都出错了,出现support_v7下面出现红线及解决方法及为什么eclipse中项目继承Actio ...
- EditPlus提示错误:找不到或无法加载主类
问题:EditPlus提示错误:找不到或无法加载主类. 原因:换了另外一台电脑,忘了什么时候,环境变量被误删了. 解决问题: 1.检查文件名和public修饰的类名是否一致. 2.文件查看时,有没有隐 ...