python splash scrapy

1.      前言

slpash是一个渲染引擎,它有自己的api,可以直接访问splash服务的http接口,但也有对应的包python-splash方便调用。

1.1.  python + splash简单调用

先从直接访问http接口开始。

import requests

from urllib.parse import quote

import re

lua = '''

function main(splash, args)

local treat = require("treat")

local response = splash:http_get("https://www.shou.edu.cn/")

return treat.as_string(response.body)

end

'''

url = 'http://splash:8050/execute?lua_source=' + quote(lua)

response = requests.get(url, auth=('admin', 'admin'))

ip = re.search('(\d+\.\d+\.\d+\.\d+)', response.text).group(1)

print(ip)

需要注意的是quote(lua),需要转码。

使用的是splash的API。

比较简单的接口,更具体的接口方法见文档http://splash.readthedocs.io/en/stable/api.html#render-html

案例:curl http://localhost:8050/render.html?url=https://www.baidu.com

url参数为目标网页地址。

2.      scrapy+splash

2.1.    安装

pip install scrapy-splash

2.2.    使用

在scrapy_splash中定义了一个SplashRequest类,用户只需使用scrapy_splash.SplashRequst来替代scrapy.Request发送请求

该构造器常用参数如下:

url---待爬取的url地址

headers---请求头

cookies---cookies信息

args---传递给splash的参数,如wait\timeout\images\js_source等

cache_args--针对参数重复调用或数据量大大情况,让Splash缓存该参数

endpoint---Splash服务端点

splash_url---Splash服务器地址,默认为None

爬虫主体代码没什么变化。

spider

# -*- coding: utf-8 -*-

import scrapy

from scrapy.http import Request, FormRequest

from scrapy.selector import Selector

from scrapy_splash.request import SplashRequest, SplashFormRequest

class JdSpider(scrapy.Spider):

name = "jd"

def start_requests(self):

splash_args = {"lua_source": """

--splash.response_body_enabled = true

splash.private_mode_enabled = false

splash:set_user_agent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36")

assert(splash:go("https://item.jd.com/5089239.html"))

splash:wait(3)

return {html = splash:html()}

"""}

yield SplashRequest("https://item.jd.com/5089239.html", endpoint='run', args=splash_args, callback=self.onSave)

def onSave(self, response):

value = response.xpath('//span[@class="p-price"]//text()').extract()

print(value)

打开jdproject/settings.py, 修改:

# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

SPIDER_MIDDLEWARES = {

'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,

}

# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html

DOWNLOADER_MIDDLEWARES = {

'scrapy_splash.SplashCookiesMiddleware': 723,

'scrapy_splash.SplashMiddleware': 725,

'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,  # 不配置查不到信息

}

HTTPCACHE_ENABLED = True

HTTPCACHE_EXPIRATION_SECS = 0

HTTPCACHE_DIR = 'httpcache'

SPLASH_URL = "http://192.168.99.100:8050/"  # 自己安装的docker里的splash位置

DUPEFILTER_CLASS = "scrapy_splash.SplashAwareDupeFilter"

HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

3.      官方文档

文档来源:https://pypi.org/project/scrapy-splash/

Add the Splash server address to settings.py of your Scrapy project like this:

SPLASH_URL = 'http://192.168.59.103:8050'

Enable the Splash middleware by adding it to DOWNLOADER_MIDDLEWARES in your settings.py file and changing HttpCompressionMiddleware priority:

DOWNLOADER_MIDDLEWARES = {

'scrapy_splash.SplashCookiesMiddleware': 723,

'scrapy_splash.SplashMiddleware': 725,

'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,

}

Order 723 is just before HttpProxyMiddleware (750) in default scrapy settings.

注意事项:

  1. 核心功能是修改url为splash_url+url,换言之就是访问splash服务器,然后返回结果,这一操作是在class SplashMiddleware(object):中完成
  2. 注意中间件的权重大小,

Enable SplashDeduplicateArgsMiddleware by adding it to SPIDER_MIDDLEWARES in your settings.py:

SPIDER_MIDDLEWARES = {

'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,

}

This middleware is needed to support cache_args feature; it allows to save disk space by not storing duplicate Splash arguments multiple times in a disk request queue. If Splash 2.1+ is used the middleware also allows to save network traffic by not sending these duplicate arguments to Splash server multiple times.

Set a custom DUPEFILTER_CLASS:

设置过滤器,有点奇怪,其实理论上应该不需要单独搞一个过滤器的,只把splash作为一个插件,

DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'

If you use Scrapy HTTP cache then a custom cache storage backend is required. scrapy-splash provides a subclass of scrapy.contrib.httpcache.FilesystemCacheStorage:

HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

If you use other cache storage then it is necesary to subclass it and replace all scrapy.util.request.request_fingerprint calls with scrapy_splash.splash_request_fingerprint.

4.      总结

可以把它理解为一个代理+浏览器,

cookie问题:由splash管理,不过建议还是在scrapy中管理,毕竟已有相关模板,另外一点是把splash的作用简单化,解耦。

代理问题:根据splash接口设置即可。

python splash scrapy的更多相关文章

  1. Python爬虫Scrapy框架入门(0)

    想学习爬虫,又想了解python语言,有个python高手推荐我看看scrapy. scrapy是一个python爬虫框架,据说很灵活,网上介绍该框架的信息很多,此处不再赘述.专心记录我自己遇到的问题 ...

  2. Python之Scrapy爬虫框架安装及简单使用

    题记:早已听闻python爬虫框架的大名.近些天学习了下其中的Scrapy爬虫框架,将自己理解的跟大家分享.有表述不当之处,望大神们斧正. 一.初窥Scrapy Scrapy是一个为了爬取网站数据,提 ...

  3. [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍

    前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...

  4. dota玩家与英雄契合度的计算器,python语言scrapy爬虫的使用

    首发:个人博客,更新&纠错&回复 演示地址在这里,代码在这里. 一个dota玩家与英雄契合度的计算器(查看效果),包括两部分代码: 1.python的scrapy爬虫,总体思路是pag ...

  5. python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)

    操作环境:python3 在上一文中python爬虫scrapy框架--人工识别知乎登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前 ...

  6. python爬虫Scrapy(一)-我爬了boss数据

    一.概述 学习python有一段时间了,最近了解了下Python的入门爬虫框架Scrapy,参考了文章Python爬虫框架Scrapy入门.本篇文章属于初学经验记录,比较简单,适合刚学习爬虫的小伙伴. ...

  7. python爬虫scrapy项目详解(关注、持续更新)

    python爬虫scrapy项目(一) 爬取目标:腾讯招聘网站(起始url:https://hr.tencent.com/position.php?keywords=&tid=0&st ...

  8. Python安装scrapy过程中出现“Failed building wheel for xxx”

    https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml Python安装scrapy库过程中出现“ Failed building wheel for xxx ...

  9. Python的scrapy之爬取顶点小说网的所有小说

    闲来无事用Python的scrapy框架练练手,爬取顶点小说网的所有小说的详细信息. 看一下网页的构造: tr标签里面的 td 使我们所要爬取的信息 下面是我们要爬取的二级页面 小说的简介信息: 下面 ...

随机推荐

  1. mysql学习笔记(1)

    以下笔记并不系统,只是针对遇到的问题和特别的点记录一下: 数据类型: 1.mysql小数存储数据类型 有float double decimal ,前两个不属于精确类型,不推荐使用,一般生产库亦不会使 ...

  2. ansible笔记(5):常用模块之命令类模块

    1.command模块 它的作用是帮助我们在远程主机上执行命令. [注意]使用command模块在远程主机中执行命令时,不会经过远程主机的shell处理,在使用command模块时,如果需要执行的命令 ...

  3. RNGCryptoServiceProvider 生成订单号

    先生成1~1000的随机数 class Program { // Create a new instance of the RNGCryptoServiceProvider. private stat ...

  4. ubuuntu截图

    方法1: 按 print screen sysrq 方法2: 系统设置 选择键盘 选择快捷键窗口 选择截图 按照自己的习惯更改快捷键即可.

  5. DataGridView单元格显示密码

    DataGridView单元格显示密码 private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormatt ...

  6. 并发之CountDownLatch用法详解

    概念 CountDownLatch 是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行.例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后执行. Co ...

  7. Android学习11

    Android存储概念 File内部存储 通过file=openFileOutput()获得,将数据存储在data/data/+包名+files下面. layout布局文件: <?xml ver ...

  8. Python - 运行流程图, call graph, 调用图

    解决方案 pycallgraph(感觉直接用pycallgraph grahviz命令生成的图并不是我想要的) 如何去阅读并学习一些优秀的开源框架的源码? - mailto1587的回答 - 知乎 h ...

  9. AJAX技术初级探索

    一 概念 Ajax技术能够实现页面以异步方式从服务器获取信息,无需刷新页面 Ajax的核心技术是XMLHttpRequest对象(XHR) 异步实际就是请求数据的代码不会阻塞页面向下执行 二 原生Aj ...

  10. 探讨LoadRunner的并发用户和集合点

    近来跟踪一个项目,发现同事们在执行性能测试时,比较热衷于使用集合点,从概念上认为要得到并发用户就必须设置集合点,认为在执行一个压力测试脚本时,设置了集合点才算是有效的并发用户,没有设置结合点,就认为可 ...