Python爬蟲:splash+requests簡單示例
說明:
render是get方式
execute是post方式
render
import requests def splash_render(url): splash_url = "http://localhost:8050/render.html" args = { "url": url, "timeout": 5, "image": 0, "proxy": "http://222.95.21.28:8888" } response = requests.get(splash_url, params=args) return response.text if __name__ == '__main__': url = "http://quotes.toscrape.com/js/" html = splash_render(url)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
args參數說明:
url: 需要渲染的頁面地址
timeout: 超時時間
proxy:代理
wait:等待渲染時間
images: 是否下載,默認1(下載)
js_source: 渲染頁面前執行的js代碼
execute
import json import requests def splash_execute(url): splash_url = "http://localhost:8050/execute" script = """ function main(splash) local url="{url}" splash:set_user_agent("Mozilla/5.0 Chrome/69.0.3497.100 Safari/537.36") splash:go(url) splash:wait(2) splash:go(url) return { html = splash:html() } end """ script = script.replace("{url}", url) data = { "timeout": 5, "lua_source": script } response = requests.post(splash_url, json=data) return response.json().get("html") if __name__ == '__main__': url = "http://quotes.toscrape.com/js/" html = splash_execute(url)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
參數說明:
timeout 超時
lua_source lua腳本
proxy 代理
模擬登錄
以下是lua腳本
splash提供的select選擇器,使用方法和jQuery類似
function main(splash, args) -- jquery加載比較慢 splash:autoload("https://code.jquery.com/jquery-3.3.1.min.js") splash:set_viewport_size(1366, 768) splash:set_user_agent("Mozilla/5.0 Chrome/69.0.3497.100 Safari/537.36") -- 從首頁點擊登錄按鈕 splash:go(splash.args.url) splash:wait(3) splash:runjs("$('#login').click()") splash:wait(2) -- 登錄頁輸入賬號密碼,并提交 splash:select("#username"):send_text("username") splash:select("#password"):send_text("password") splash:wait(5) -- 可以使用splash自帶的鼠標點擊,并指定點擊位置 local button = splash:select("#button") local bounds = button:bounds() button:mouse_click{x=bounds.width/3, y=bounds.height/3} splash:wait(2) -- 返回 return { html=splash:html(), png = splash:png(), cookie=splash:get_cookies() } end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
參考:
splash文檔:https://splash.readthedocs.io/en/stable/scripting-ref.html
Python
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。