理, 参考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://www.hmttv.cn/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://www.hmttv.cn/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小时内与您取得联系。