浏览器模拟器之Splash的使用

Splash Lua脚本使用方法

  • 基本实例:
function main(splash, args)
  assert(splash:go(args.url))
  assert(splash:wait(0.5))
  return {
    html = splash:html(),
    png = splash:png(),
    har = splash:har(),
  }
end

返回值形式:
字典形式
return {hello=“word!”}
返回一个字符串格式
return “hello”
最后都会转化为Splash HTTP Response

  • 异步处理
function main(splash, args)
local example_urls = {"www.baidu.com","www.taobao.com","www.zhihu.com"}
 assert(splash:go(args.url))
 assert(splash:wait(0.5))
 return {
   html = splash:html(),
   png = splash:png(),
   har = splash:har(),
 }
end

Splash对象的属性

args获取加载配置时的参数 ,如url,get请求中获取参数,post请求中获取表单数据
js_enabled设置JsvaScript是否开启,默认为truesplash.js_enabled = false/true
resourse_timeout设置加载的超时时间,单位是秒splash.resourse_out = 0.1
images_enabled设置图片是否加载,默认为truesplash.images_enabled = false/true
plugins_emabled设置浏览器插件是否加载,默认为falsesplash.plugins_emabled = true/false
scroll_position控制页面上下火左右滚动splash.scroll_position = {y=400}

Splash对象的方法

go()请求链接

用来请求某个链接,可模拟POST和GET请求,支持请求头表单等数据

ok, reason = splash:go{url,baseurl=nil,headers=nil,http_method='GET',body=nil,formdata=nil}
参数说明
URL请求的URL
baseurl可选参数,默认为空,表示资源的相对加载路径
headers可选参数,默认为空,表示请求头
http_method可选参数,默认为GET,同时支持POST
body可选参数,默认为空,发POST请求时的表单数据,使用的Content-type为Json
formdata可选参数,默认为空,发POST请求时的表单数据,使用的Content-type为x-www-form-urlencoded
function main(splash,args)
	local ok, reason = splash:go{"http://httpbin.org/post",http_method="POST",body="name=Germey"}
	if ok then
		return splash:html()

wait()延时等待

用来控制页面等待时间

ok, reason = splash:wait{timecancel_on_redirect=false,cancel_on_error=true}
参数说明
time等待的秒数
cancel_on_redirect可选参数,默认为false,如果为true,表示如果发生了重定向就停止等待,返回重定向结果
cancel_on_error可选参数,默认为true,表示如果发生了加载错误就停止等待,返回结果同样是ok和原因reason的组合
function main(splash):
	splash:go("https://www.taobao.com")
	splash:wait(2)
	return {html=splash:html()}
end

jsfunc()

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

function main(splash,args)
	local get_div_count = splash:jsfunc([[
	function () {
		var body =document.body;
		var divs = body.getElementsByTagName(div");
		return divs.length;
	}
	]])
	splash:go("https://www.baidu.com")
	return ("there are %s DIVs"):format(
		get_div_count())
end

evaljs()

此方法可以执行JavaScript代码并返回最后一条JavaScript语句的返回结果

result = splash:evaljs("document.title")

runjs()

此方法可以执行JavaScript代码,它与evaljs()的功能类似,但是更偏向于执行某些动作或声明或某些方法,例如:

function main(splash,args)
	splash:go("网址")
	splash:runjs("foo = function() { return 'bar' }")
	local result = splash:evaljs("foo()")
	return result 
end

autoload()

此方法可以设置页面访问时自动加载的对象,只负责加载不执行任何操作,如需执行可以调用evaljs()或runjs()

ok,reason = splash:autoload{source_or_url,source=nil,url=nil}
参数说明
source_or_urlJavaScript代码或者JavaScript库链接。
sourseJavaScript代码
urlJavaScript库链接

call_later()

此方法可以设置定时任务和延迟时间来实现任务延时执行,并且可以再执行前通过canncel()重新执行定时任务

--lua语言中--为注释
function main(splash, args)
  -- 定义了一个存储截图的列表
  local snapshots = {}
  --定义一个定时任务函数
  local timer = splash:call_later(function()
      snapshots['a'] = splash:png()
      splash:wait(1,0)
      snapshots['b'] = splash:png()
  end,0.2)
  splash:go('https://www.taobao.com')
  splash:wait(3.0)
  --返回截图结果
  return snapshots
end

http_get()

此方法模拟发送http的get请求,使用方法如下

response = splash:http_get{url,headers=nil, follow_redirects=true}
参数说明
url请求URL
headers可选参数、默认为空,请求头
follow_redirects可选参数,表示是否启动自动重定向,默认为True
--lua语言中--为注释
function main(splash, args)
--扩展模块在使用前需要引用
  local treat = require('treat')
  local response  = splash:http_get('http://httpbin.org/get')
  	return {
    	html=treat.as_string(response.body),
    	url=response.url,
    	status=response.status
  	}
end

http_post()

response = splash:http_post{url, headers=nil, follow_redirects=true, body=nil
参数说明
url请求URL
headers可选参数、默认为空,请求头
follow_redirects可选参数,表示是否启动自动重定向,默认为True
body可选参数,及表单数据,默认为空
--lua语言中--为注释
function main(splash, args)
  local treat = require('treat')
  local json = require('json')
  local response  = splash:http_post{'http://httpbin.org/post',
  	body=json.encode({name='Germey'}),
  	headers={['content-type']='application/json'}}
  	return {
    	html=treat.as_string(response.body),
    	url=response.url,
    	status=response.status
  	}
end

set_content()

此方法用来设置页面内容

--lua语言中--为注释
function main(splash)
  assert(splash:set_content('<html><h1>hello</h1></html>'))
  return splash:png()
end

html()

此方法用来获取网页的源代码

--lua语言中--为注释
function main(splash, args)
  splash:go('https://www.baidu.com')
  return splash:html()
end

png()

此方法用来获取PNG格式网页截图

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

jpeg()

此方法用来获取JPEG格式网页截图

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

har() 获取页面加载过程

此方法用来获取页面加载过程

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

url()

此方法可以获取当前正在访问的URL,实例如下

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

get_cookies()

此方法可以获取当前页面的Cookies

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

add_cookie{}

此方法可以为当前页面添加Cookie

cookies = splash:add_cookies{name,value,path=nil,domain=nil,expires=nil,httpOnly=nil,secure=nil}
function main(splash, args)
  local message = {}
  splash:add_cookie{'BAIDUID_BFESS','Ccccc80DD9DD055F969CFDBC7DEE:FG=1','/',domain='http://baidu.com'}
  splash:go('http://www.baidu.com/')
  message['png'] = splash:png()
  message['cookies'] = splash:get_cookies()  
  return message
end

clear_cookies()

此方法可以清除所有Cookies

function main(splash, args)
  splash:go('http://www.baidu.com/')
  splash:clear_cookies()
  return splash:get_cookies()
end

get_viewport_size()

此方法可以获取当前浏览器页面的大小,即宽高

function main(splash, args)
  splash:go('http://www.baidu.com/')
  return splash:get_viewport_size()
end

set_viewport_size()

此方法可以设置当前浏览器页面的大小,即宽高

function main(splash, args)
  splash:set_viewport_size(400,700)
  --assert()条件成立继续操作 不成立就报错
  assert(splash:go('http://www.baidu.com/'))
  return splash:get_viewport_size()
end

set_viewport_full()

此方法可以最大化当前浏览器页面

function main(splash, args)
  splash:set_viewport_full()
  --assert()条件成立继续操作 不成立就报错
  assert(splash:go('http://www.baidu.com/'))
  return splash:get_viewport_size()
end

set_user_agent()

此方法可以设置浏览器的UA

function main(splash)
  splash:set_user_agent('splash-lol')
  --assert()条件成立继续操作 不成立就报错
  assert(splash:go('http://httpbin.org/get'))
  return splash:html()
end

sent_custom_headers()

此方法可以设置请求头

function main(splash)
  splash:set_user_agent('splash-lol')
  --assert()条件成立继续操作 不成立就报错
  assert(splash:go('http://httpbin.org/get'))
  return splash:html()
end

select() send_text()

可以选中符合条件的第一个节点

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

select_all()

此方法可以选中所有符合条件的节点,参数是CSS选择器,然后可以遍历节点

function main(splash)
  local treat = require('treat')
  assert(splash:go('http://quotes.toscrape.com/'))
  assert(splash:wait(0.5))
  local texts = splash:select_all('.quote .text')
  local results = {}
  for index, text in ipairs(texts) do
        results[index] = text.node.innerHTML
  end
  splash:wait(3)
  return treat.as_array(results)
end

mouse_click()

此方法可以模拟鼠标点击操作,传入的参数为坐标轴xy,也可以选择节点

function main(splash, args)
  assert(splash:go('http://www.baidu.com'))
  input = splash:select('#kw')
  input:send_text('splash')
  submit = splash:select('#su')
  submit:mouse_click()
  submit = splash:select('#su')
  submit:mouse_click()
  splash:wait(5)
  return splash:png()
end

Splash API调用

以上的Lua脚本实在Splash的测试页面中进行的,以下API是结合Python程序调用的

render.html

这个接口用于获取Js渲染页面的HTML代码

  • 用curl实现
curl http://localhost:8050?render.html?url=https://www.baidu.com
  • 用Python实现
import requests
url = 'http://localhost:8050?render.html?url=https://www.baidu.com'
response = requests.get(url)
print(response.text)
  • 指定其他参数
    wait指定等待秒数
import requests
url = 'http://localhost:8050?render.html?url=https://www.baidu.com&wait=5'
response = requests.get(url)
print(response.text)

代理设置
图片加载设置
Headers设置
请求方法设置

render.png

此接口可以获取网页截图,参数比render.html多了几个,比如截图长宽

  • 用curl实现
curl http://localhost:8050?render.png?url=https://www.baidu.com&wait=5&width=1000&height=700
  • 用python实现
import requests
url = 'http://localhost:8050?render.html?url=https://www.baidu.com&wait=5&width=1000&height=700'
response = requests.get(url)
with open('picture.png', 'wb') as f:
   f.write(response.content)

render.jpeg

比上面多了个参数quality来设置图片质量

runder.har

此接口用于获取页面加载的HAR数据

curl http://localhost:8050?render.har?url=https://www.baidu.com&wait=5

runder.json

包含了前面接口的所有功能,返回的结果是json格式

curl http://localhost:8050?render.json?url=https://www.baidu.com&html=1&har=1

execute最重要的

用此接口可以实现与复杂lua脚本的对接,脚本例子如下

function mian(splash)
	return 'hello'
end

脚本转化成url编码后的字符串

curl http://localhost:8050/execute?lua_sourse=function=main%28splash%29%oD
%oA++return+%27hello%27%oD
%oAend
  • Python实现
import requests
from urllib.parse import quote

lua='''
function main(splash, args)
    local treat = require('treat')
    local response = splash:http_get('http://httpbin.org/get')
    return{
        html = treat.as_string(response.body),
        url = response.url,
        status = response.status
    }
end
'''

url = 'http://localhost:8050/execute?lua_source='+quote(lua)
response = requests.get(url)
print(response.text)

Splash对接Scrapy

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值