[Python3网络爬虫开发实战] --Splash的使用

2023-10-24 17:40

本文主要是介绍[Python3网络爬虫开发实战] --Splash的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Splash是一个JavaScript渲染服务,是一个带有HTTP API的轻量级浏览器,同时它对接了Python中的Twisted和QT库。利用它同样可以实现动态渲染页面的抓取。

1. 功能介绍

利用Splash可以实现如下功能:

  • 异步方式处理多个网页渲染过程;
  • 获取渲染后的页面的源代码或截图;
  • 通过关闭图片渲染或者使用Adblock规则来加快页面渲染速度;
  • 可执行特定的JavaScript脚本;
  • 可通过Lua脚本来控制页面渲染过程;
  • 获取渲染的详细过程并通过HAR(HTTP Archive)格式呈现。

2. 准备工作

在开始之前,请确保已经正确安装好了Splash并可以正常运行服务(pip install Splash)。

3. 实例引入

首先,通过Splash提供的Web页面来测试其渲染过程。例如,在本机8050端口上运行了Splash服务,打开http://localhost:8050/即可看到其Web页面,如图1所示。
在这里插入图片描述
在图1右侧,呈现的是一个渲染示例。可以看到,上方有一个输入框,默认是http://google.com,这里换成百度测试一下,将内容更改为https://www.baidu.com,然后点击Render me按钮开始渲染,结果如图2所示。
在这里插入图片描述
可以看到,网页的返回结果呈现了渲染截图、HAR加载统计数据、网页的源代码。

通过HAR的结果可以看到,Splash执行了整个网页的渲染过程,包括CSS、JavaScript的加载等过程,呈现的页面和在浏览器中得到的结果完全一致。

那么,这个过程由什么来控制呢?重新返回首页,可以看到实际上是有一段脚本,内容如下:

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

这个脚本实际上是用Lua语言写的脚本。即使不懂这个语言的语法,但从脚本的表面意思,也可以大致了解到它首先调用go()方法去加载页面,然后调用wait()方法等待了一定时间,最后返回了页面的源码、截图和HAR信息。

到这里,大体了解了Splash是通过Lua脚本来控制了页面的加载过程的,加载过程完全模拟浏览器,最后可返回各种格式的结果,如网页源码和截图等。

接下来就来了解Lua脚本的写法以及相关API的用法。

4. Splash Lua脚本

Splash可以通过Lua脚本执行一系列渲染操作,这样就可以用Splash来模拟类似Chrome、PhantomJS的操作了。

首先,了解一下Splash Lua脚本的入口和执行方式。

入口及返回值
首先,来看一个基本实例:

function main(splash, args)splash:go("http://www.baidu.com")splash:wait(0.5)local title = splash:evaljs("document.title")return {title=title}
end

将代码粘贴到刚才打开的http://localhost:8050/的代码编辑区域,然后点击Render me!按钮来测试一下。

看到它返回了网页的标题,如图7-8所示。这里通过evaljs()方法传入JavaScript脚本,而document.title的执行结果就是返回网页标题,执行完毕后将其赋值给一个title变量,随后将其返回。
在这里插入图片描述
注意,在这里定义的方法名称叫作main()。这个名称必须是固定的,Splash会默认调用这个方法。

该方法的返回值既可以是字典形式,也可以是字符串形式,最后都会转化为Splash HTTP Response,例如:

function main(splash)return {hello="world!"}
end

返回了一个字典形式的内容。例如:

function main(splash)return 'hello'
end

返回了一个字符串形式的内容。

异步处理

Splash支持异步处理,但是这里并没有显式指明回调方法,其回调的跳转是在Splash内部完成的。示例如下:

function main(splash, args)local example_urls = {"www.baidu.com", "www.taobao.com", "www.zhihu.com"}local urls = args.urls or example_urlslocal results = {}for index, url in ipairs(urls) dolocal ok, reason = splash:go("http://" .. url)if ok thensplash:wait(2)results[url] = splash:png()endendreturn results
end

运行结果是3个站点的截图,如图3所示。
在这里插入图片描述
在脚本内调用的wait()方法类似于Python中的sleep(),其参数为等待的秒数。当Splash执行到此方法时,它会转而去处理其他任务,然后在指定的时间过后再回来继续处理。

这里值得注意的是,Lua脚本中的字符串拼接和Python不同,它使用的是…操作符,而不是+。如果有必要,可以简单了解一下Lua脚本的语法,详见http://www.runoob.com/lua/lua-basic-syntax.html。

另外,这里做了加载时的异常检测。go()方法会返回加载页面的结果状态,如果页面出现4xx或5xx状态码,ok变量就为空,就不会返回加载后的图片。

5. Splash对象属性

注意到,前面例子中main()方法的第一个参数是splash,这个对象非常重要,它类似于Selenium中的WebDriver对象,可以调用它的一些属性和方法来控制加载过程。接下来,先看下它的属性。

args

该属性可以获取加载时配置的参数,比如URL,如果为GET请求,它还可以获取GET请求参数;如果为POST请求,它可以获取表单提交的数据。Splash也支持使用第二个参数直接作为args,例如:

function main(splash, args)local url = args.url
end

这里第二个参数args就相当于splash.args属性,以上代码等价于:

function main(splash)local url = splash.args.url
end

js_enabled

这个属性是Splash的JavaScript执行开关,可以将其配置为true或false来控制是否执行JavaScript代码,默认为true。例如,这里禁止执行JavaScript代码:

function main(splash, args)splash:go("https://www.baidu.com")splash.js_enabled = falselocal title = splash:evaljs("document.title")return {title=title}
end

接着重新调用了evaljs()方法执行JavaScript代码,此时运行结果就会抛出异常:

{"error": 400,"type": "ScriptError","info": {"type": "JS_ERROR","js_error_message": null,"source": "[string \"function main(splash, args)\r...\"]","message": "[string \"function main(splash, args)\r...\"]:4: unknown JS error: None","line_number": 4,"error": "unknown JS error: None","splash_method": "evaljs"},"description": "Error happened while executing Lua script"
}

不过一般来说,不用设置此属性,默认开启即可。

resource_timeout

此属性可以设置加载的超时时间,单位是秒。如果设置为0或nil(类似Python中的None),代表不检测超时。示例如下:

function main(splash)splash.resource_timeout = 0.1assert(splash:go('https://www.taobao.com'))return splash:png()
end

例如,这里将超时时间设置为0.1秒。如果在0.1秒之内没有得到响应,就会抛出异常,错误如下:

{"error": 400,"type": "ScriptError","info": {"error": "network5","type": "LUA_ERROR","line_number": 3,"source": "[string \"function main(splash)\r...\"]","message": "Lua error: [string \"function main(splash)\r...\"]:3: network5"},"description": "Error happened while executing Lua script"
}

此属性适合在网页加载速度较慢的情况下设置。如果超过了某个时间无响应,则直接抛出异常并忽略即可。

images_enabled

此属性可以设置图片是否加载,默认情况下是加载的。禁用该属性后,可以节省网络流量并提高网页加载速度。但是需要注意的是,禁用图片加载可能会影响JavaScript渲染。因为禁用图片之后,它的外层DOM节点的高度会受影响,进而影响DOM节点的位置。因此,如果JavaScript对图片节点有操作的话,其执行就会受到影响。

另外值得注意的是,Splash使用了缓存。如果一开始加载出来了网页图片,然后禁用了图片加载,再重新加载页面,之前加载好的图片可能还会显示出来,这时直接重启Splash即可。

禁用图片加载的示例如下:

function main(splash, args)splash.images_enabled = falseassert(splash:go('https://www.jd.com'))return {png=splash:png()}
end

这样返回的页面截图就不会带有任何图片,加载速度也会快很多。

plugins_enabled

此属性可以控制浏览器插件(如Flash插件)是否开启。默认情况下,此属性是false,表示不开启。可以使用如下代码控制其开启和关闭:

splash.plugins_enabled = true/false

scroll_position

通过设置此属性,可以控制页面上下或左右滚动。这是一个比较常用的属性,示例如下:

function main(splash, args)assert(splash:go('https://www.taobao.com'))splash.scroll_position = {y=400}return {png=splash:png()}
end

这样就可以控制页面向下滚动400像素值,结果如图4所示。
在这里插入图片描述
如果要让页面左右滚动,可以传入x参数,代码如下:

splash.scroll_position = {x=100, y=200}

6. Splash对象的方法

除了前面介绍的属性外,Splash对象还有如下方法。

go()

该方法用来请求某个链接,而且它可以模拟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变量中包含了错误的原因,否则证明页面加载成功。示例如下:

function main(splash, args)local ok, reason = splash:go{"http://httpbin.org/post", http_method="POST", body="name=Germey"}if ok thenreturn splash:html()end
end

这里模拟了一个POST请求,并传入了POST的表单数据,如果成功,则返回页面的源代码。

运行结果如下:

<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": "60.207.237.85", "url": "http://httpbin.org/post"
}
</pre></body></html>

可以看到成功实现了POST请求并发送了表单数据。

wait()

此方法可以控制页面的等待时间,使用方法如下:

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

参数说明如下。

  • time:等待的秒数。
  • cancel_on_redirect:可选参数,默认为false,表示如果发生了重定向就停止等待,并返回重定向结果。
  • cancel_on_error:可选参数,默认为false,表示如果发生了加载错误,就停止等待。
    返回结果同样是结果ok和原因reason的组合。

用一个实例感受一下:

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

这可以实现访问淘宝并等待2秒,随后返回页面源代码的功能。

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

运行结果如下:

There are 21 DIVs

首先,声明了一个JavaScript定义的方法,然后在页面加载成功后调用了此方法计算出了页面中div节点的个数。

关于JavaScript到Lua脚本的更多转换细节,可以参考官方文档:https://splash.readthedocs.io/en/stable/scripting-ref.html#splash-jsfunc。

evaljs()

此方法可以执行JavaScript代码并返回最后一条JavaScript语句的返回结果,使用方法如下:

result = splash:evaljs(js)

比如,可以用下面的代码来获取页面标题:

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

runjs()

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

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

这里用runjs()先声明了一个JavaScript定义的方法,然后通过evaljs()来调用得到的结果。

运行结果如下:

bar

autoload()

此方法可以设置每个页面访问时自动加载的对象,使用方法如下:

ok, reason = splash:autoload{source_or_url, source=nil, url=nil}

参数说明如下。

  • source_or_url:JavaScript代码或者JavaScript库链接。
  • source:JavaScript代码。
  • url:JavaScript库链接

但是此方法只负责加载JavaScript代码或库,不执行任何操作。如果要执行操作,可以调用evaljs()或runjs()方法。示例如下:

function main(splash, args)splash:autoload([[function get_document_title(){return document.title;}]])splash:go("https://www.baidu.com")return splash:evaljs("get_document_title()")
end

这里调用autoload()方法声明了一个JavaScript方法,然后通过evaljs()方法来执行此JavaScript方法。

运行结果如下:

百度一下,你就知道

另外,也可以使用autoload()方法加载某些方法库,如jQuery,示例如下:

function main(splash, args)assert(splash:autoload("https://code.jquery.com/jquery-2.1.3.min.js"))assert(splash:go("https://www.taobao.com"))local version = splash:evaljs("$.fn.jquery")return 'JQuery version: ' .. version
end

运行结果如下:

JQuery version: 2.1.3

call_later()

此方法可以通过设置定时任务和延迟时间来实现任务延时执行,并且可以在执行前通过cancel()方法重新执行定时任务。示例如下:

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

这里设置了一个定时任务,0.2秒的时候获取网页截图,然后等待1秒,1.2秒时再次获取网页截图,访问的页面是淘宝,最后将截图结果返回。运行结果如图5所示。
在这里插入图片描述
可以发现,第一次截图时网页还没有加载出来,截图为空,第二次网页便加载成功了。

http_get()

此方法可以模拟发送HTTP的GET请求,使用方法如下:

response = splash:http_get{url, headers=nil, follow_redirects=true}

参数说明如下。

  • url:请求URL。
  • headers:可选参数,默认为空,请求头。
  • follow_redirects:可选参数,表示是否启动自动重定向,默认为true。
    示例如下:
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

运行结果如下:

Splash Response: Object
html: String (length 355)
{"args": {}, "headers": {"Accept-Encoding": "gzip, deflate", "Accept-Language": "en,*", "Connection": "close", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) splash Version/9.0 Safari/602.1"}, "origin": "60.207.237.85", "url": "http://httpbin.org/get"
}
status: 200
url: "http://httpbin.org/get"

http_post()

和http_get()方法类似,此方法用来模拟发送POST请求,不过多了一个参数body,使用方法如下:

response = splash:http_post{url, headers=nil, follow_redirects=true, body=nil}

参数说明如下。

url:请求URL。
headers:可选参数,默认为空,请求头。
follow_redirects:可选参数,表示是否启动自动重定向,默认为true。
body:可选参数,即表单数据,默认为空。
用实例感受一下:

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

运行结果如下:

Splash Response: Object
html: String (length 533)
{"args": {}, "data": "{\"name\": \"Germey\"}", "files": {}, "form": {}, "headers": {"Accept-Encoding": "gzip, deflate", "Accept-Language": "en,*", "Connection": "close", "Content-Length": "18", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) splash Version/9.0 Safari/602.1"}, "json": {"name": "Germey"}, "origin": "60.207.237.85", "url": "http://httpbin.org/post"
}
status: 200
url: "http://httpbin.org/post"

可以看到,这里成功模拟提交了POST请求并发送了表单数据。

set_content()

此方法用来设置页面的内容,示例如下:

function main(splash)assert(splash:set_content("<html><body><h1>hello</h1></body></html>"))return splash:png()
end

运行结果如图6所示。
在这里插入图片描述

html()

此方法用来获取网页的源代码,它是非常简单又常用的方法。示例如下:

function main(splash, args)splash:go("https://httpbin.org/get")return splash:html()
end

运行结果如下:

<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{"args": {}, "headers": {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en,*", "Connection": "close", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) splash Version/9.0 Safari/602.1"}, "origin": "60.207.237.85", "url": "https://httpbin.org/get"
}
</pre></body></html>

png()

此方法用来获取PNG格式的网页截图,示例如下:

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

jpeg()

此方法用来获取JPEG格式的网页截图,示例如下:

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

har()

此方法用来获取页面加载过程描述,示例如下:

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

运行结果如图7所示,其中显示了页面加载过程中每个请求记录的详情。
在这里插入图片描述

url()

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

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

运行结果如下:

https://www.baidu.com/

get_cookies()

此方法可以获取当前页面的Cookies,示例如下:

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

运行结果如下:

Splash Response: Array[2]
0: Object
domain: ".baidu.com"
expires: "2085-08-21T20:13:23Z"
httpOnly: false
name: "BAIDUID"
path: "/"
secure: false
value: "C1263A470B02DEF45593B062451C9722:FG=1"
1: Object
domain: ".baidu.com"
expires: "2085-08-21T20:13:23Z"
httpOnly: false
name: "BIDUPSID"
path: "/"
secure: false
value: "C1263A470B02DEF45593B062451C9722"

add_cookie()

此方法可以为当前页面添加Cookie,用法如下:

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

该方法的各个参数代表Cookie的各个属性。

示例如下:

function main(splash)splash:add_cookie{"sessionid", "237465ghgfsd", "/", domain="http://example.com"}splash:go("http://example.com/")return splash:html()
end

clear_cookies()

此方法可以清除所有的Cookies,示例如下:

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

这里清除了所有的Cookies,然后调用get_cookies()将结果返回。

运行结果如下:

Splash Response: Array[0]

可以看到,Cookies被全部清空,没有任何结果。

get_viewport_size()

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

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

运行结果如下:

Splash Response: Array[2]
0: 1024
1: 768

set_viewport_size()

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

splash:set_viewport_size(width, height)

例如,这里访问一个宽度自适应的页面:

function main(splash)splash:set_viewport_size(400, 700)assert(splash:go("http://cuiqingcai.com"))return splash:png()
end

运行结果如图8所示。
在这里插入图片描述

set_viewport_full()

此方法可以设置浏览器全屏显示,示例如下:

function main(splash)splash:set_viewport_full()assert(splash:go("http://cuiqingcai.com"))return splash:png()
end

set_user_agent()

此方法可以设置浏览器的User-Agent,示例如下:

function main(splash)splash:set_user_agent('Splash')splash:go("http://httpbin.org/get")return splash:html()
end

这里将浏览器的User-Agent设置为Splash,运行结果如下:

<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{"args": {}, "headers": {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en,*", "Connection": "close", "Host": "httpbin.org", "User-Agent": "Splash"}, "origin": "60.207.237.85", "url": "http://httpbin.org/get"
}
</pre></body></html>

可以看到,此处User-Agent被成功设置。

set_custom_headers()

此方法可以设置请求头,示例如下:

function main(splash)splash:set_custom_headers({["User-Agent"] = "Splash",["Site"] = "Splash",})splash:go("http://httpbin.org/get")return splash:html()
end

这里设置了请求头中的User-Agent和Site属性,运行结果如下:

<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{"args": {}, "headers": {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en,*", "Connection": "close", "Host": "httpbin.org", "Site": "Splash", "User-Agent": "Splash"}, "origin": "60.207.237.85", "url": "http://httpbin.org/get"
}
</pre></body></html>

select()

该方法可以选中符合条件的第一个节点,如果有多个节点符合条件,则只会返回一个,其参数是CSS选择器。示例如下:

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

这里首先访问了百度,然后选中了搜索框,随后调用了send_text()方法填写了文本,然后返回网页截图。

结果如图9所示,可以看到成功填写了输入框。
在这里插入图片描述

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) doresults[index] = text.node.innerHTMLendreturn treat.as_array(results)
end

这里通过CSS选择器选中了节点的正文内容,随后遍历了所有节点,将其中的文本获取下来。

运行结果如下:

Splash Response: Array[10]
0: "“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”"
1: "“It is our choices, Harry, that show what we truly are, far more than our abilities.”"
2: “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.3: "“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”"
4: "“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”"
5: "“Try not to become a man of success. Rather become a man of value.”"
6: "“It is better to be hated for what you are than to be loved for what you are not.”"
7: "“I have not failed. I've just found 10,000 ways that won't work.”"
8: "“A woman is like a tea bag; you never know how strong it is until it's in hot water.”"
9: "“A day without sunshine is like, you know, night.”"

可以发现成功地将10个节点的正文内容获取了下来。

mouse_click()

此方法可以模拟鼠标点击操作,传入的参数为坐标值x和y。此外,也可以直接选中某个节点,然后调用此方法,示例如下:

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

这里首先选中页面的输入框,输入了文本,然后选中“提交”按钮,调用了mouse_click()方法提交查询,然后页面等待三秒,返回截图,结果如图10所示。
在这里插入图片描述
可以看到,这里成功获取了查询后的页面内容,模拟了百度搜索操作。

前面介绍了Splash的常用API操作,还有一些API在这不再一一介绍,更加详细和权威的说明可以参见官方文档https://splash.readthedocs.io/en/stable/scripting-ref.html,此页面介绍了Splash对象的所有API操作。另外,还有针对页面元素的API操作,链接为https://splash.readthedocs.io/en/stable/scripting-element-object.html。

7. Splash API调用

前面说明了Splash Lua脚本的用法,但这些脚本是在Splash页面中测试运行的,如何才能利用Splash渲染页面呢?怎样才能和Python程序结合使用并抓取JavaScript渲染的页面呢?

其实Splash提供了一些HTTP API接口,只需要请求这些接口并传递相应的参数即可,下面简要介绍这些接口。

render.html

此接口用于获取JavaScript渲染的页面的HTML代码,接口地址就是Splash的运行地址加此接口名称,例如http://localhost:8050/render.html。可以用curl来测试一下:

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

给此接口传递了一个url参数来指定渲染的URL,返回结果即页面渲染后的源代码。

如果用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.taobao.com&wait=5'
response = requests.get(url)
print(response.text)

此时得到响应的时间就会相应变长,比如这里会等待5秒多钟才能获取淘宝页面的源代码。

另外,此接口还支持代理设置、图片加载设置、Headers设置、请求方法设置,具体的用法可以参见官方文档https://splash.readthedocs.io/en/stable/api.html#render-html。

render.png

此接口可以获取网页截图,其参数比render.html多了几个,比如通过width和height来控制宽高,它返回的是PNG格式的图片二进制数据。示例如下:

curl http://localhost:8050/render.png?url=https://www.taobao.com&wait=5&width=1000&height=700

这里传入了width和height来设置页面大小为1000×700像素。

如果用Python实现,可以将返回的二进制数据保存为PNG格式的图片,具体如下:

import requestsurl = 'http://localhost:8050/render.png?url=https://www.jd.com&wait=5&width=1000&height=700'
response = requests.get(url)
with open('taobao.png', 'wb') as f:f.write(response.content)

得到的图片如图11所示。
在这里插入图片描述
这样就成功获取了京东首页渲染完成后的页面截图,详细的参数设置可以参考官网文档https://splash.readthedocs.io/en/stable/api.html#render-png。

render.jpeg

此接口和render.png类似,不过它返回的是JPEG格式的图片二进制数据。

另外,此接口比render.png多了参数quality,它用来设置图片质量。

render.har

此接口用于获取页面加载的HAR数据,示例如下:

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

它的返回结果(如图12所示)非常多,是一个JSON格式的数据,其中包含页面加载过程中的HAR数据。
在这里插入图片描述

render.json

此接口包含了前面接口的所有功能,返回结果是JSON格式,示例如下:

curl http://localhost:8050/render.json?url=https://httpbin.org

结果如下:

{"title": "httpbin(1): HTTP Client Testing Service", "url": "https://httpbin.org/", "requestedUrl": "https://httpbin.org/", "geometry": [0, 0, 1024, 768]}

可以看到,这里以JSON形式返回了相应的请求数据。

可以通过传入不同参数控制其返回结果。比如,传入html=1,返回结果即会增加源代码数据;传入png=1,返回结果即会增加页面PNG截图数据;传入har=1,则会获得页面HAR数据。例如:

curl http://localhost:8050/render.json?url=https://httpbin.org&html=1&har=1

这样返回的JSON结果会包含网页源代码和HAR数据。

此外还有更多参数设置,具体可以参考官方文档:https://splash.readthedocs.io/en/stable/api.html#render-json。

execute

此接口才是最为强大的接口。前面说了很多Splash Lua脚本的操作,用此接口便可实现与Lua脚本的对接。

前面的render.html和render.png等接口对于一般的JavaScript渲染页面是足够了,但是如果要实现一些交互操作的话,它们还是无能为力,这里就需要使用execute接口了。

先实现一个最简单的脚本,直接返回数据:

function main(splash)return 'hello'
end

然后将此脚本转化为URL编码后的字符串,拼接到execute接口后面,示例如下:

curl http://localhost:8050/execute?lua_source=function+main%28splash%29%0D%0A++return+%27hello%27%0D%0Aend

运行结果如下:

hello

这里通过lua_source参数传递了转码后的Lua脚本,通过execute接口获取了最终脚本的执行结果。

这里更加关心的肯定是如何用Python来实现,上例用Python实现的话,代码如下:

import requests
from urllib.parse import quotelua = '''
function main(splash)return 'hello'
end
'''url = 'http://localhost:8050/execute?lua_source=' + quote(lua)
response = requests.get(url)
print(response.text)

运行结果如下:

hello

这里用Python中的三引号将Lua脚本包括起来,然后用urllib.parse模块里的quote()方法将脚本进行URL转码,随后构造了Splash请求URL,将其作为lua_source参数传递,这样运行结果就会显示Lua脚本执行后的结果。

再通过实例看一下:

import requests
from urllib.parse import quotelua = '''
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)

运行结果如下:

{"url": "http://httpbin.org/get", "status": 200, "html": "{\n  \"args\": {}, \n  \"headers\": {\n    \"Accept-Encoding\": \"gzip, deflate\", \n    \"Accept-Language\": \"en,*\", \n    \"Connection\": \"close\", \n    \"Host\": \"httpbin.org\", \n    \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) splash Version/9.0 Safari/602.1\"\n  }, \n  \"origin\": \"60.207.237.85\", \n  \"url\": \"http://httpbin.org/get\"\n}\n"}

可以看到,返回结果是JSON形式,成功获取了请求的URL、状态码和网页源代码。

如此一来,之前所说的Lua脚本均可以用此方式与Python进行对接,所有网页的动态渲染、模拟点击、表单提交、页面滑动、延时等待后的一些结果均可以自由控制,获取页面源码和截图也都不在话下。

到现在为止,可以用Python和Splash实现JavaScript渲染的页面的抓取了。除了Selenium,本节所说的Splash同样可以做到非常强大的渲染功能,同时它也不需要浏览器即可渲染,使用非常方便。

这篇关于[Python3网络爬虫开发实战] --Splash的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/276760

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没