python-爬虫-scrapy
入门:
下载:pip install scrapy
工程:scrapy startproject 工程名
Spider: scrapy genspider 爬虫名 url (--nolog//可选不显示日志)
简介:
持久化存储:
1 :终端存储:scrapy crawl -o aaa.text
2 : 管道存储:items对象即穿过来的{}字典,之后存储
3: open_spider()---->链接数据库,close_spider()-->关闭数据库,process_item()--->存储
代理Ip:
1自定义下载中间件
middleware.py---》
class MyProxy(object):
def process_request(self,request,spider):
# 请求ip 更换
request.meta['proxy'] = "http://202.112.51.51:8082"
2 开启下载中间件
DOWNLOADER_MIDDLEWARES = {
'firstBlood.middlewares.MyProxy': 543,
}
日志等级:
1
ERROR:错误
WARNING:警告
INFO:一般信息
DEBUG:调试信息(默认)
指定日志信息等级:
settings:LOG_LEVEL = ‘ERROR’
将日志信息存储到制定文件中:
settings:LOG_FILE = ‘log.txt’
2 二级传参
yield scrapy.Request(url=url,callback=self.secondParse,meta={'item':ite
m})
调用:item = response.meta['item']
请求传参:
方式一:用scrapy.Requests(method='post')
方式二:重写start_request(self)方法(推荐)
class FanyiSpider(scrapy.Spider):
def start_requests(self):
data = {
'kw':'dog'
}
for url in self.start_urls:
# FormRequest发送post请求
yield scrapy.FormRequest(url=url,formdata=data,callback=self.parse)
CrawlSpider:
一般多层请求是多少层多少方法,或递归方法--->yield scrapy.Request(url,callback,meta)
特殊请求有多种:
一:初始请求化作请求队列,功能(获取url列表,不断请求,在新页面获取新url列表)
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class CrawlspiderSpider(CrawlSpider):
name = 'crawlSpider'
start_urls = ['https://www.qiushibaike.com/text']
rules = ( Rule(LinkExtractor(allow=r'/text/page/\d+'), callback='parse_item', follow=True),)
'''
LinkExtractor : 设置提取链接的规则(正则表达式)
allow=(), : 设置允许提取的url
restrict_xpaths=(), :根据xpath语法,定位到某一标签下提取链接
restrict_css=(), :根据css选择器,定位到某一标签下提取链接
deny=(), : 设置不允许提取的url(优先级比allow高)
allow_domains=(), : 设置允许提取url的域
deny_domains=(), :设置不允许提取url的域(优先级比allow_domains高)
unique=True, :如果出现多个相同的url只会保留一个
strip=True :默认为True,表示自动去除url首尾的空格
'''
'''
rule
link_extractor, : linkExtractor对象
callback=None, : 设置回调函数
follow=None, : 设置是否跟进
process_links=None, :可以设置回调函数,对所有提取到的url进行拦截
process_request=identity : 可以设置回调函数,对request对象进行拦截
'''
def parse_item(self, response):
div_list = response.xpath('//div[@id="content‐left"]/div')
for div in div_list:
item = PhpmasterItem()
author = div.xpath('./div/a[2]/h2/text()').extract_first()
item['author'] = str(author).strip()
# print(author)
content = div.xpath('./a[1]/div/span/text()').extract()
content = ''.join(content)
item['content'] = str(content).strip()
yield item
二:下载img时,把img_url传到管道中,管道中下载(请求方入下级)
Spider::yield item[‘img_url’]
Setting::IMAGES_STORE = './images/'
Pip::
from qiubaipic.settings import IMAGES_STORE as images_store
from scrapy.pipelines.images import ImagesPipeline
class QiubaipicPipeline(ImagesPipeline):
def get_media_requests(self, item, info):
img_link = "http:"+item['img_link']
yield scrapy.Request(img_link)
图片分组:
def file_path(self, request, response=None, info=None):
'''完成图片存储路径'''
img_name = request.url.split('/')[-1] # 图片名
file_name = request.meta['file_name'] # 路径
image_guid = file_name + '/' + img_name # 天价世界名画/2560580770.jpg
img_path = IMAGES_STORE + file_name + '/' # ./image/天价世界名画/ 必须存在
if not os.path.exists(img_path):
os.makedirs(img_path)
print(request.url)
return '%s' % (image_guid)
分布式爬虫:
代理IP池和UA池
代理ip中间件:
http_list = []
https_list = []
def process_request(self, request, spider):
h = request.url.split(':')[0]
if h == 'http':
http = 'http://'+random.choice(http_list)
if h == 'https':
http = 'https://'+random.choice(https_list)
request.meta['proxy'] = http
Ua中间件:
user_agent_list = []
def process_request(self, request, spider):
#从列表中随机抽选出一个ua值
ua = random.choice(user_agent_list)
# 4. ua值进行当前拦截到请求的ua的写入操作
request.headers.setdefault('User-Agent',ua)
脚本运行scrapy项目:
项目下新建xxx.py;
from scrapy import cmdline
# 帮助我们直接执行scrapy 命令
cmdline.execute('scrapy crawl logrule --nolog'.split())
python-爬虫-scrapy的更多相关文章
- python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)
操作环境:python3 在上一文中python爬虫scrapy框架--人工识别知乎登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前 ...
- python爬虫Scrapy(一)-我爬了boss数据
一.概述 学习python有一段时间了,最近了解了下Python的入门爬虫框架Scrapy,参考了文章Python爬虫框架Scrapy入门.本篇文章属于初学经验记录,比较简单,适合刚学习爬虫的小伙伴. ...
- python爬虫scrapy项目详解(关注、持续更新)
python爬虫scrapy项目(一) 爬取目标:腾讯招聘网站(起始url:https://hr.tencent.com/position.php?keywords=&tid=0&st ...
- Python爬虫Scrapy框架入门(0)
想学习爬虫,又想了解python语言,有个python高手推荐我看看scrapy. scrapy是一个python爬虫框架,据说很灵活,网上介绍该框架的信息很多,此处不再赘述.专心记录我自己遇到的问题 ...
- [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...
- 安装python爬虫scrapy踩过的那些坑和编程外的思考
这些天应朋友的要求抓取某个论坛帖子的信息,网上搜索了一下开源的爬虫资料,看了许多对于开源爬虫的比较发现开源爬虫scrapy比较好用.但是以前一直用的java和php,对python不熟悉,于是花一天时 ...
- Python 爬虫-Scrapy爬虫框架
2017-07-29 17:50:29 Scrapy是一个快速功能强大的网络爬虫框架. Scrapy不是一个函数功能库,而是一个爬虫框架.爬虫框架是实现爬虫功能的一个软件结构和功能组件集合.爬虫框架是 ...
- python爬虫scrapy学习之篇二
继上篇<python之urllib2简单解析HTML页面>之后学习使用Python比较有名的爬虫scrapy.网上搜到两篇相应的文档,一篇是较早版本的中文文档Scrapy 0.24 文档, ...
- Python爬虫Scrapy(二)_入门案例
本章将从案例开始介绍python scrapy框架,更多内容请参考:python学习指南 入门案例 学习目标 创建一个Scrapy项目 定义提取的结构化数据(Item) 编写爬取网站的Spider并提 ...
- python爬虫----scrapy框架简介和基础应用
Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以 ...
随机推荐
- mysql_config_editor设置
[root@node01 etc]# mysql_config_editor set -G mysql3307 -S /tmp/mysql3307.sock -uroot -pEnter passwo ...
- Educational Codeforces Round 33 (Rated for Div. 2) D题 【贪心:前缀和+后缀最值好题】
D. Credit Card Recenlty Luba got a credit card and started to use it. Let's consider n consecutive d ...
- Can't load Microsoft.ReportViewer.ProcessingObjectModel.dll
本机的时候是能正常看到report,但deploy到别的机器上却不行,按说从本机拷个dll过去就可以,但怎么也找不到. 原来要在cmd那里输入C:\WINDOWS\assembly\GAC_MSIL ...
- UVAlive 7414 Squeeze the Cylinders a,b,c三种步数 搜索+最短路
题意:给你n个点(n<=50),然后有些点之间会有一条路,路是单向的,每个回合让你走a,b,c三种步数中的任意一种(a,b,c<=100),问你最少需要多少个回合才能保证一定能从1点到达n ...
- 无法连接虚拟设备 ide1:0及上不网
无法连接虚拟设备 ide1:0 问题: 启动vmware之后,发现出现无法连接 ide 1:0. 网络查找之后,发现是之前挂载的iso镜像找不到了. 原因: 我把iso镜像放到其他位置. 解决: 指定 ...
- centos与debian网卡
debian /etc/network/interfaces # This file describes the network interfaces available on your sys ...
- 8. 使用Zuul构建微服务网关
使用Zuul构建微服务网关 8.1. 为什么要使用微服务网关 8.2. Zuul简介 8.3. 编写Zuul微服务网关 8.4. Zuul的路由端点 8.5. Zuul ...
- flask 第十篇 after_request before_request
Flask我们已经学习很多基础知识了,现在有一个问题 我们现在有一个 Flask 程序其中有3个路由和视图函数,如下: from flask import Flask app = Flask(__na ...
- python排序之冒泡排序
def sort(list): for i in range(len(list)): for j in range(len(list) - i - 1): if list[j] < list[j ...
- 转载: Windows下两种iocp实现的差距
转自:http://blog.csdn.net/oldworm/article/details/6171430 之前几天说过,因为经典iocp实现(以下简称经典实现)多个io线程绑定在一个iocp上, ...