selenium是浏览器测试自动化工具,很容易完成鼠标点击,翻页等动作,确定是一次只能加载一个页面,无法异步渲染页面,也就限制了selenium爬虫的抓取效率。

splash可以实现异步渲染页面,可以同时渲染几个页面。缺点是在页面点击,,模拟登陆方面没有selenium灵活。

1、docker安装splash

docker安装splash镜像
[ywadmin@wzy_woyun ~]$docker pull scrapinghub/splash
#后台运行
[ywadmin@wzy_woyun ~]$ docker run -d -p 8050:8050 --name=splash scrapinghub/splash
#root用户开放8050端口
[root@wzy_woyun ~]# firewall-cmd --permanent --add-port=8050/tcp
success
[root@wzy_woyun ~]# firewall-cmd --reload
Success

2、splash中的对象

2.1、args属性

该属性可以获取加载时配置的参数,比如url。

function main(splash, args)

local url = args.url

end

上面的代码等同于下面

function main(splash, args)

local url = splash.args.url

end

3.2、js_enabled属性

接着我们重新代用eval()方法执行JavaScript代码,运行时发现报错。这个属性是splash的JavaScript执行开关,可以将其配置为true或者false来控制是否执行JavaScript代码,默认为true

function main(splash, args)splash:go("https://www.baidu.com")splash:js_enabled = false -- 禁止加载JavaScript代码splash:wait(0.5)local title = splash:evaljs("document.title") --获取网页标题return {html = splash:html(),title = title,   }
end

接着我们重新代用eval()方法执行JavaScript代码,运行时发现报错。

一般不用设置次属性,默认是开启的。

2.3、resource_timeout属性

属性可以设置加载的超时时间,单位是秒。如果设置为0或者nil(类似py中的None),表示不进行超时检测。

function main(splash, args)splash.resource_timeout = 5splash:go("https://www.taobao.com")return splash:html()
end

2.4、images_enabled属性

images_enabled属性表示可以设置图片是否加载,默认情况下是加载的,默认为true。如果设置图片不加载,那么加载网页速度会快。

function main(splash, args)splash.images_enabled = falsesplash:go("https://www.taobao.com")return {splash:html(),splash.png}
end

2.5、plugins_enabled属性

该属性表示是否开启浏览器插件。默认情况是开启,默认值为true。

function main(splash, args)splash.plugins_enabled = falsesplash:go("https://www.taobao.com")return {splash:html(),splash.png(),}
end

2.6、scroll_position属性

控制浏览页面上下或者左右滚动,这个属性是比较常用的属性。

function main(splash, args) splash:go("https://www.taobao.com")splash.scroll_postion={x=300,y=500}return {splash:html(),splash.png()}
end

其中x=300表示向右移动300像素,y=500表示向下移动500像素。

3、splash中的方法

3.1、go()方法

go方法用来请求某个链接,而且它可以模拟get和post请求,同时支持传入请求头、表单等数据。

function main(splash)splash:go{"http://www.sxt.cn", http_method="POST", body="name=17703181473"}splash:wait(2)return {html=splash:html()}
end

3.2、wait()方法

wait()方法控制页面的等待时间:

splash:wait{time, cancel_on_redirect=false, cancel_on_error=true}

function main(splash)splash:go("https://www.taobao.com")splash:wait(2)return {html=splash:html()}
end

3.3、jsfunc()方法

直接调用JavaScript定义的方法,但是所调用的方法需要用双中括号包围,这相当于实现了JavaScript方法到Lua脚本的转换。

function main(splash, args)splash:go("http://www.baidu.cn")local scroll_to = splash:jsfunc("window.scrollTo")scroll_to(0, 300)return {png = splash:png(),html = splash:html()}
end

3.4、evaljs()方法和runjs()方法

function main(splash, args)splash:go("https://www.baidu.com")splash:runjs("foo = function() { return 'sxt' }")local result = splash:evaljs("foo()")return result
end

3.5、send_text()

send_text()方法是填写文本的功能

function main(splash)splash:go("https://www.baidu.com/")input = splash:select("#kw")input:send_text('Splash')splash:wait(3)return splash:png()
end

3.6、url()方法

获取当前在访问的URL

function main(splash, args)splash:go("https://www.baidu.com")return splash:url()
end

3.7、get_cookies()方法

function main(splash, args)splash:go("http://www.baidu.com")splash:wait(2)local cookies = splash:get_cookies()return {cookies = cookies,html = splash:html(),png = splash:png(),har = splash:har(),}
end

3.7、  add_cookie()方法

添加cookies

【语法】

cookies = splash:add_cookie{name, value, path=nil, domain=nil, expires=nil, httpOnly=nil, secure=nil}

function main(splash)splash:add_cookie{"sessionid", "123456abcdef", "/", domain="http://bjsxt.com"}splash:go("http://bjsxt.com/")return splash:html()
end

3.8、clear_cookies()方法

function main(splash)splash:go("https://www.bjsxt.com/")splash:clear_cookies()return splash:get_cookies()
end

3.9、set_user_agent()方法

function main(splash, args)splash:set_user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")splash:go("http://httpbin.org/get")splash:wait(5)return {html = splash:html(),png = splash:png(),   }
end

注意set_user_agent()方法后面直接跟具体的值。

3.10、set_custom_headers()方法

set_custom_headers()方法是用来设置请求头信息。

function main(splash, args)splash:set_custom_headers({["User-Agent"]="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",["Host"]="www.httpbin.org"})splash:go("http://httpbin.org/get")splash:wait(5)return {html = splash:html(),png = splash:png(),   }
end

4、splash与python整合

Splash与Python结合其实就python调用splash的api。

4.1、render.html应用

import requests
from urllib.parse import quote
# 1、render.html
# 次接口用于获取JavaScript渲染的页面的HTML代码,接口地址就是Splash的运行地址加次接口名称,如http://192.168.2.10:8050/render.html
url = "http://192.168.2.10:8050/render.html?url=http://www.hnwznz.com&wait=2"
response = requests.get(url)
print(response.text)# 2、render.png 此接口可以获取网页截图
url_2= "http://192.168.2.10:8050/render.png?url=https://www.jd.com&wait=3&width=1000&height=700"
response_2 = requests.get(url_2)
with open("jd.png","wb") as f:f.write(response.content)

4.2、execute的调用

#3、execute 作为最强大的接口,用次接口便可实现与Lua脚本的对接。lua = """
function main(splash, args)return "hello"
end
"""
url_3 = "http://192.168.2.10:8050/execute?lua_source="+quote(lua)
response_3 = requests.get(url_3)
print(response_3.text)

【例子】

import requests
from fake_useragent import UserAgent
from urllib.parse import quote
url = "https://www.guazi.com/bj/buy/"
lua_script = '''
function main(splash, args)splash:go('{}')splash:wait(1)return splash:html()
end
'''.format(url)
splash_url = "http://192.168.2.10:8050/execute?lua_source={}".format(quote(lua_script))
response = requests.get(splash_url, headers={"User-Agent": UserAgent().random})
response.encoding = 'utf-8'
print(response.text)

5、应用例子

5.1、爬取京东商品

import json
import requests
from lxml import etree
from urllib.parse import quote
lua = '''
function main(splash, args)local treat = require("treat")local response = splash:http_get("https://search.jd.com/Search?keyword=相机&enc=utf-8")return {html = treat.as_string(response.body),url = response.url,status = response.status}
end
'''
# 线上部署的服务,需要将localhost换成服务器的公网地址(不是内网地址)
url = 'http://192.168.2.10:8050/execute?lua_source=' + quote(lua)
response = requests.get(url)
# 由于使用splash,response.text返回结果为{"status":200,"html":"xxxxxxxxx","url":"yyyyyy"}
html = json.loads(response.text)['html']
# print(html)
tree = etree.HTML(html)# 单品
products_1 = tree.xpath('//div[@class="gl-i-wrap"]')
for item in products_1:try:name_1 = item.xpath('./div[@class="p-name p-name-type-2"]/a/em/text()')[0]price_1 = item.xpath('./div[@class="p-price"]/strong/@data-price | ./div[@class="p-price"]/strong/i/text()')[0]print(name_1)print(price_1)except:pass
print("="*90)

基础篇(6) splash应用相关推荐

  1. 鸟哥的Linux私房菜(基础篇)- 第二十六章、Linux 核心编译与管理

    第二十六章.Linux核心编译与管理 最近升级日期:2009/09/18 我们说的 Linux 其实指的就是核心 (kernel) 而已.这个核心控制你主机的所有硬件并提供系统所有的功能,所以说,他重 ...

  2. Python Qt GUI设计:信号与槽的使用方法(基础篇—7)

    目录 1.信号与槽的概念 2.信号与槽的基础函数 2.1.创建信号函数 2.2.连接信号函数 2.3.断开信号函数 2.4.发射信号函数 3.信号和槽的使用方法 3.1.内置信号与槽的使用 3.2.自 ...

  3. Python Qt GUI设计:窗口布局管理方法【强化】(基础篇—6)

    目录 1. 水平布局类(QHBoxLayout) 2.垂直布局类(QVBoxLayout) 3.网格布局类(QGridLayout) 3.1.单一的网络布局 3.2.跨越行.列的网络布局 4.表单布局 ...

  4. Python Qt GUI设计:窗口布局管理方法【基础】(基础篇—5)

    目录 1.布局管理器进行布局 2.容器控件进行布局 3.geometry属性:控件绝对布局 4.sizePolicy属性:微调优化控件布局 Qt Designer提供4种窗口布局方式,分别如下: Ve ...

  5. ES6 你可能不知道的事 – 基础篇

    ES6 你可能不知道的事 – 基础篇 转载 作者:淘宝前端团队(FED)- 化辰 链接:taobaofed.org/blog/2016/07/22/es6-basics/ 序 ES6,或许应该叫 ES ...

  6. python多线程并发_Python进阶记录之基础篇(二十四)

    回顾 在Python进阶记录之基础篇(二十三)中,我们介绍了进程的基本概念以及Python中多进程的基本使用方法.其中,需要重点掌握多进程的创建方法.进程池和进程间的通信.今天我们讲一下Python中 ...

  7. 基础篇9-python基本数据结构-列表

    基础篇9-python基本数据结构-列表 一.列表: 1.有序的集合 2.通过偏移来索引,从而读取数据 3.支持内嵌 a =[[1,2,3],[4,5,6]] 4.可变类型 a[0][1] = 7 二 ...

  8. Linq初级班 Linq To XML体验(基础篇)

    LINQ To XML体验(基础) 这两天开始学习LINQ to XML的知识,我会继续把自己的感想和示例发布给初学者们学习的,一样欢迎高手们多多指点,请勿使用过激语言,针锋相对,我是个初学者,自知还 ...

  9. php 爬虫_Scrapy 爬虫完整案例-基础篇

    1 Scrapy 爬虫完整案例-基础篇 1.1 Scrapy 爬虫案例一 Scrapy 爬虫案例:爬取腾讯网招聘信息 案例步骤: 第一步:创建项目. 在 dos下切换到目录 D:爬虫_scriptsc ...

最新文章

  1. Linux 终端命令行提示符的艺术--PS1进阶
  2. 关于Less的学习笔记
  3. python3 lambda函数字典排序_排序字典表理解中的lambda函数
  4. Google Bigtable
  5. Chrome OS 云里雾里
  6. 回顾 | 使用Visual Studio Code进行端到端应用程序开发
  7. windows下面使用nssm设置新的服务实现开机自启等
  8. [PyTorch] 深度学习框架PyTorch中的概念和函数
  9. java私塾 代码_【整理】java私塾教程课后习题
  10. DAC0832的多功能信号/波形发生器Proteus仿真设计,4种波形(正弦、三角、方波、锯齿),附仿真+C程序+论文等
  11. ACM PKU 题目分类(完整整理版本)
  12. [iOS开发]Instruments工具的学习
  13. Raptor制作猜数游戏流程图
  14. Gson解析遇到的异常分析与记录
  15. Apache端口占用解决办法
  16. 新突破!德国MPQ证实光子是量子比特载波的优选
  17. android 图片上动态添加文字,摘抄 android图片中添加文字水印
  18. 万万没想到:对JS代码混淆,竟造成这样的性能损失?
  19. Vue Echarts风向折线图拐点生成
  20. GPS从入门到放弃(十一)、差分GPS

热门文章

  1. ReLU激活函数的快速介绍
  2. [BZOJ 2085]POI2010 Hamsters
  3. Unity中的shadows(四)collect shadows
  4. phpMyAdmin 必须启用 Cookies 才能登录
  5. c语言输出时%d,%c这些都分别代表什么
  6. 基于Java+SpringBoot+Vue前后端分离学生管理系统设计与实现
  7. linux 配置开机自启动命令
  8. 【科研论文】写作技巧及文献管理工具
  9. 管理与远见,是CEO必须要注意的
  10. 使用 UML 服务组件表示 SOA 体系结构模式