一、介紹
Splash
跟之前我們介紹的 Selenium ( 參考 Selenium 與自動化測試 —— 《Selenium 2 自動化測試實戰》讀書筆記) 很類似,都可以理解成一個瀏覽器,提供網頁動態渲染(css、javascript、flash 等)服務,並且都支持 HTTP API 與之交互。
但不同點在於:
-
Splash 更輕量級,但缺點是功能沒有Selenium豐富。(所以 Selenium 才稱得上是自動化測試框架,Splash更多的算一種網頁渲染服務)
-
Splash 的安裝、配置、使用更簡單
-
Splash 支持異步,能提高爬取效率
文檔地址:https://splash.readthedocs.io/en/stable/
二、安裝
注意:事先安裝好 docker。
docker run -p 8050:8050 scrapinghub/splash
部署在遠程服務器記得加 -d 參數,它代表將 Docker 容器以守護態運行,這樣在斷開遠程服務器連接后,不會終止 Splash 服務的運行。
三、使用
安裝好后,打開 http://localhost:8050
即可訪問,頁面如下:
本文安裝版本為 v3.4。
可以在此 web 頁面來使用,也可以用下面介紹的 API 調用方式,更靈活。
三、Splash API 調用
http://localhost:8050/render.html?url=https://www.baidu.com
http://localhost:8050/render.png?url=https://www.baidu.com
http://localhost:8050/render.jpeg?url=https://www.baidu.com
http://localhost:8050/render.har?url=https://www.baidu.com
http://localhost:8050/render.json?url=https://www.baidu.com
除了上面指定的最簡單的url、render類型,還可以通過 Lua 腳本執行更復雜的渲染操作和交互邏輯(即用 execute)。
我們用 python 代碼為例:
import requests
from urllib.parse import quote
lua = """
function main(splash)
return 'hello'
end
"""
url = 'http://localhost:8050/execute?lua_source=' + quote(lua)
response = requests.get(url)
print(response.text)
下面我們對 Lua 腳本的寫法做更多的介紹。
四、Splash 的 Lua 腳本
1、base demo
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
接下來針對這個最基本的 demo,來展開介紹。
2、main() 函數
main 函數就是 splash 默認要調用的函數,所以這里保持固定寫法就好。
而 main 的返回值,既可以是字典形式,也可以是字符串形式,最后都會轉化為 HTTP Response。
3、splash 對象
splash 類似於 Selenium 中的 WebDriver 對象。
(1)splash 屬性
上面提到的 main 函數的第二個參數 args 其實是 splash 對象的其中一個屬性,即:
splash.args = args
splash.resource_timeout = 0.1 - 設置超時時間。如果設置為 0 或 nil (類似 Python 中的None),代表不檢測超時。
此屬性適合在網頁加載速度較慢的情況下設置
splash.js_enabled = false - 是否執行 js(默認為 ture)
splash.images_enabled = false 是否加載圖片(默認為 ture)
小心 image 不加載導致個別 DOM 渲染出錯
splash.plugins_enabled = false - 是否加載瀏覽器插件,如 Flash 插件 (默認 false)
splash.scroll_position = {x=100, y=200} = 頁面上下或左右滾動
(3)splash 方法
go() - 模擬 GET 和 POST 請求
http_get() - 模擬 GET 請求
http_post() - 模擬 POST 請求
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()
end
end
wait() - 等待。類似 python 中的 sleep(多與 go 配合,緊接在 go 后面)
為什么 splash 沒有 selenium 的 expected_conditions(預期條件判斷)方法,如presence_of_element_located。
call_later() - 類似 JavaScript 的 settimeout
evaljs() - 執行 js 代碼
local title = splash:evaljs("document.title")
runjs() 跟 evaljs() 功能類似,只不過語義上更傾向於只調用不關心返回值。
autoload() 跟 evaljs() 功能類似,只不過語義上更傾向於預先加載。
jsfunc() - JavaScript 方法轉換為 Lua 腳本
這個好,畢竟我 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
url() - 獲取/設置 url
html() / set_content() - 獲取/設置 html 內容
splash:set_content ("
hello ")
png() / jpeg() - 獲取頁面截圖
har() - 獲取頁面加載過程描述
get_cookies() / add_cookie() / clear_ cookies() - 獲取/設置/清除 html 內容
splash:add_cookie({"sessionid", "asdasd", "/", domain="http://example.com" })
set_user_agent() - 設置 user-agent
set_custom_headers() - 設置 header
自定義程度更高,可以設置 user_agent、cookies 等等
splash:set_custom_headers({
["User-Agent"] = "Splash",
["Site"] = "Splash",
})
get_viewport_size() / set_viewport_size(width, height) - 獲取/設置頁面大小
set_viewport_full() - 設置全屏
select() - css 選擇器 (選擇首個)
input = splash:select("#kw”)
-- 點擊控件
input:mouse_click()
-- 給控件輸入文本
input:send_text('Splash')
selectAll() - css 選擇器 (選擇全部)
-- 通過 css 選擇器選中了節點的正文內容,隨后遍歷了所有節點,將其中的文本獲取下來
local texts = splash:select_all('.quote .text')
local results = {}
for index, text in ipairs(texts) do
results[index] = text.node.innerHTML
end
五、Splash 負載均衡配置
待寫。具體可看原書。
六、參考資料
《Python 3網絡爬蟲開發實戰》