爬虫之Splash对象方法(一)
一 go()
1 点睛
该方法用来请求某个链接,而且它可以模拟GET和POST请求,同时支持传入请求头、表单等数据,其用法如下:
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为application/json。
- formdata:可选参数,默认为空,POST的时候的表单数据,使用的Content-type为application/x-www-form-urlencoded。
该方法的返回结果是结果ok和原因reason的组合,如果ok为空,代表网页加载出现了错误,此时reason变量中包含了错误的原因,否则证明页面加载成功。
2 示例
2.1 代码
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
2.2 结果
<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{
"args": {},
"data": "",
"files": {},
"form": {
"name": "Germey"
},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en,*",
"Connection": "close",
"Content-Length": "11",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"Origin": "null",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) splash Version/9.0 Safari/602.1"
},
"json": null,
"origin": "1.86.245.33",
"url": "http://httpbin.org/post"
}
</pre></body></html>
二 wait()
1 点睛
此方法可以控制页面的等待时间,使用方法如下:
ok, reason = splash:wait{time, cancel_on_redirect=false, cancel_on_error=true}
参数说明如下。
- time:等待的秒数。
- cancel_on_redirect:可选参数,默认为false,表示如果发生了重定向就停止等待,并返回重定向结果。
- cancel_on_error:可选参数,默认为false,表示如果发生了加载错误,就停止等待。
返回结果同样是结果ok和原因reason的组合。
2 代码
function main(splash)
splash:go("https://www.taobao.com")
splash:wait(2)
return {html=splash:html()}
end
3 结果
三 jsfunc()
1 点睛
此方法可以直接调用JavaScript定义的方法,但是所调用的方法需要用双中括号包围,这相当于实现了JavaScript方法到Lua脚本的转换。
2 代码
function main(splash, args)
assert(splash:go(args.url))
assert(splash:wait(0.5))
return {
html = splash:html(),
png = splash:png(),
har = splash:har(),
}
3 结果
Splash Response: "There are 22 DIVs"
4 说明
首先,我们声明了一个JavaScript定义的方法,然后在页面加载成功后调用了此方法计算出了页面中div节点的个数。
关于JavaScript到Lua脚本的更多转换细节,可以参考官方文档:https://splash.readthedocs.io/en/stable/scripting-ref.html#splash-jsfunc。
四 evaljs()
1 点睛
此方法可以执行JavaScript代码并返回最后一条JavaScript语句的返回结果。使用方法如下:
result = splash:evaljs(js)
比如,可以用下面的代码来获取页面标题:
local title = splash:evaljs("document.title")
五 runjs()
1 点睛
此方法可以执行JavaScript代码,它与evaljs()的功能类似,但是更偏向于执行某些动作或声明某些方法。
2 代码
function main(splash, args)
splash:go("https://www.baidu.com")
splash:runjs("foo = function() { return 'bar' }")
local result = splash:evaljs("foo()")
return result
end
3 结果
Splash Response: "bar"
4 说明
这里我们用runjs()先声明了一个JavaScript定义的方法,然后通过evaljs()来调用得到的结果。