理, 參考python Selenium.
Rust 對應的支持庫: thirtyfour.
thirtyfour 是一個用于在 Rust 中使用 WebDriver / Selenium 生態系統自動化 Web 瀏覽器的 crate。它還為 Chrome DevTools 協議提供了一些支持,Cypress 和 Playwright 等流行框架都使用了該協議。
它旨在成為一個 "batteries-included "的框架,用于所有與 Web 瀏覽器自動化相關的事物,尤其是 Web 應用程序的自動化測試
本次實驗采用chrome瀏覽器,windows 系統下.
請先下載chrome瀏覽器的webdriver. 注意版本一定要跟當前chrome瀏覽器版本一致.
https://chromedriver.chromium.org/downloads
Step 1:
手動啟動 chromedriver.exe 或者自動啟動,代碼如下:
將chromedriver.exe復制到當前項目目錄.
let dir = current_dir().unwrap();
let exe = dir.join("chromedriver.exe");
Command::new(exe)
.spawn()
.expect("啟動[chromedriver.exe]失敗!");
Step2:
連接webseriver. webservier將監聽在本機9515端口.
let username="test0000";
let password="test0001";
// caps 支持啟動參數. 具體請參考api.
let mut caps = DesiredCapabilities::chrome();
// 連接到web driver.
let driver = WebDriver::new("http://127.0.0.1:9515", caps).await?;
/// 載入登錄頁面.
driver.goto("https://login.xxxx.xxxx.com/cse/#/login").await?;
/// 找到輸入手機號的地方. xpath, input輸入框,提示符為請輸入手機號.
let elem_phone = driver.find(By::XPath("//input[@placeholder='請輸入手機號']")).await?;
/// 輸入賬號.
elem_phone.send_keys(username).await?;
///找到密碼輸入框. id是login-pwd. 通過F12 查找元素去找規則.
let elem_password = driver.find(By::Id("login-pwd")).await?
/// 輸入密碼.
elem_password.send_keys(password).await?;
/// 找到登錄按鈕.
let login_btn = driver.find(By::ClassName("ui-login-from__btn")).await?;
// 點擊登錄按鈕.
login_btn.click().await?;
通過查找html元素找到元素的匹配規則,再做操作.
API 參考文檔:
https://stevepryde.github.io/thirtyfour/introduction.html
固定時間等待.
//等待3秒.
sleep(Duration::from_secs(3)).await;
查詢只到某個元素出現,看以下代碼,這個地方會阻塞.
// 等待,只到元素出現或者超時為止.
let login_btn = driver.find(By::ClassName("ui-login-from__btn")).first().await?;
一些對安全性要求比較高的網站比如網銀會對密碼輸入采用專用控件. 甚至對輸入的鍵碼進行了加密,
這種情況下send_keys是不會起作用的,可行的解決方案是采用驅動級的虛擬鍵盤,模擬鍵盤操作.來實現功能.
本文采用DD虛擬鍵盤來實現.
通過rust ffi接口,調用DD虛擬鍵盤的DLL.
DD虛擬鍵盤項目地址:
https://github.com/ddxoft/master
封裝示例代碼如下.
/// DD 虛擬鍵盤.
fn load_dd_virtual_kb()->Result<Library, Box<dyn std::error::Error>> {
unsafe {
let lib = libloading::Library::new("dd40605x64.dll")?;
return Ok(lib) ;
}
}
fn dd_btn(lib:&Library, btn: i32) -> Result<(), Box<dyn std::error::Error>>{
unsafe {
let func: libloading::Symbol<unsafe extern fn(i32)> = lib.get(b"DD_btn")?;
func(btn);
Ok(())
}
}
// 注意,rust 字符串與c str的內存布局和結束符是不同的.
fn dd_press_key(lib:&Library, key:&str) -> Result<(), Box<dyn std::error::Error>> {
unsafe {
let v = CString::new(key).unwrap();
let func: libloading::Symbol<unsafe extern fn(*const c_char)> = lib.get(b"DD_str")?;
// info!("Press Key:{}", key);
let c_pr: *const c_char = v.as_ptr();
func(c_pr);
Ok(())
}
}
// 慢慢按 1秒1個
async fn dd_press_key_slow(lib:&Library, keys:&str) -> Result<(), Box<dyn std::error::Error>> {
for c in keys.chars() {
let r = dd_press_key(&lib, format!("{}", c).as_str())?;
sleep(Duration::from_millis(1000)).await;
}
Ok(())
}
則上面輸入密碼框的做法是.
反爬蟲技術
爬蟲技術
隨機User-Agent設置
百度輸入:scrapy user agent 獲取隨機的agent列表
爬蟲的偽裝
動態IP接入指南
IP代理中間件編寫
Setting中配置Middleware
如果不進行偽裝則我們每次采用相同IP抓取數據時可以會被目前服務器的防火墻之別,偽裝有兩種:配置代理IP和user-agent中間件編寫,需要先注冊阿布云
注冊阿布云之后,可以選擇1元購買1小時進行動態IP的測試。如果購買成功打開對應的接入指南會有提示scrapy的相關配置
根據上面的接入指南,采用創建一個ProxyMiddleware配置相關的信息即可完成動態IP的配置
登錄驗證的API推薦
滑動驗證碼破解平臺:http://api.4xx3.cn/
云打碼:http://www.yundama.com/price.html
超級鷹:http://www.chaojiying.com/cases.html
如何發送登錄表單
由于是表單,必須發送一個Post請求,因此創建FromRequest請求,并且設置登錄成功后要執行的方法
如果登錄成功則會執行after_login方法,此方法會把登錄成功之后的頁面下載到本地,下載時設置的編碼取決于目標網頁的編碼
PIL庫基本介紹
完成登錄驗證碼識別操作
友有一臺電腦需要連接公共WIFI,該WIFI支持賬號登錄、手機驗證碼登錄和微信登錄,但是一次登錄成功后,第二天早上會自動清理登錄賬號,因此需要一個方法每天自動登錄WIFI。之前朋友使用Python爬蟲方法模擬用戶點擊輸入賬號和密碼登錄,但是經常出現無法正常連接的狀況,于是找我看看如何優化。
1、 在瀏覽器中輸入www.baidu.com,會自動跳轉到WIFI登錄認證界面。
curl www.baidu.com
使用curl模擬,獲取返回的頁面信息如下:
<html>
<head>
<script type="text/javascript">location.href="http://10.131.6.1:8080/wsmAuth/iportal/?usermac=34-F7-16-79-XX-XX&userip=10.131.50.166&ssid=FREE%2dWIFI&nasip=10%2e131%2e6%2e1&devType=v7"</script>
</head>
<body>
Authentication is required. Click <a href="http://10.131.6.1:8080/wsmAuth/iportal/?usermac=34-F7-16-79-XX-XX&userip=10.131.50.166&ssid=FREE%2dWIFI&nasip=10%2e131%2e6%2e1&devType=v7">here</a> to open the authentication page.
</body>
</html>
其中usermac和userip是當前電腦的mac地址和自動獲取的IP。
2、使用chrome調試模式獲取賬戶登錄form提交內容。
可以看到該form使用post方法向/wsmAuth/login提交了一堆參數,其中重要的是username(用戶名)、signature(密碼)、usermac(mac地址)、userip(ip地址)、ssid(wifi名稱)、nasip(認證服務器IP)、devType(設備類型)、userAgreement(登錄協議勾選)。
以上參數用戶名密碼我們有,其他參數均可以從跳轉頁面鏈接中獲取。
3、測試直接提交登錄認證是否可以登錄成功。
curl http://10.131.6.1:8080/wsmAuth/login -X POST -d "operateType=7&signature=XXXXXX&userName=135xxxxxxxx&userAgreement=1&rabbit=h3c&templateId=7&redirect_uri=null&apmac=null&usermac=34-F7-16-79-XX-XX&userip=10.131.50.166&userurl= &shopid=1&groupid=0&authCfgid=1&ssid=FREE-WIFI&basip=null&nasid=null&wlannasid=null&wlanssid=null&userPublicIp=null&nasip=10.131.6.1&devType=v7&ipmAuthType=1&authPage=/themeTemplate/1638770462964/auth.xml&onebutton=0&userLabel=&needWechat=1"
登錄成功!
HTTP/1.1 200 OK
Content-Type: text/json;charset=UTF-8
Content-Length: 179
{"succurl":"http://10.131.6.1:8080/wsmAuth/succ_page.jsp?templateId=7&shopid=1&ssid=FREE-WIFI&succpage=/themeTemplate/1638770462964/complete.xml&groupid=0&userLabel="}
使用上面的方法登錄成功說明該WIFI認證并沒有COOKIE、REFERE等驗證,這將簡化自動登錄程序。我們完全不需要用朋友寫的模擬瀏覽器點擊的方案了,代碼量和代碼復雜度極大降低!
4、 再次訪問www.baidu.com測試網絡是否正常。
可以正常訪問外網!
curl www.baidu.com -i
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: keep-alive
Content-Length: 2381
Content-Type: text/html
Date: Tue, 15 Mar 2022 02:31:09 GMT
Etag: "588604eb-94d"
Last-Modified: Mon, 23 Jan 2017 13:28:11 GMT
Pragma: no-cache
Server: bfe/1.0.8.18
Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新聞</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地圖</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>視頻</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>貼吧</a> <noscript> <a href=http://m.jungjaehyung.com/uploadfile/2024/0808/20240808042912402.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登錄</a> </noscript> <script>document.write('<a href="http://m.jungjaehyung.com/uploadfile/2024/0808/20240808042912402.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登錄</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多產品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>關于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>?2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必讀</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a> 京ICP證030173號 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
總結:
通過上面幾個簡單的步驟,成功模擬了使用用戶名密碼登錄該WIFI的步驟,接下來就是寫一個腳本自動登錄了。
自動登錄腳本思路如下:
具體代碼將使用Python的requests編寫,詳見下篇文章。
連載:自動連接公共WIFI(二):python腳本自動連接
*請認真填寫需求信息,我們會在24小時內與您取得聯系。