2015年12月4日
phantomjs模拟登录小米
phantomjs模拟登录小米应该是一种非常逼真的模拟浏览器登录的一种方式,不需要去拼凑各种POST参数,与C#中的webbrowser比较类似。这里分享如何在C#工程中使用phantomjs来模拟登陆小米商城。
1.首先我们需要在我们的C#工程中添加NReco.PhantomJS,添加方法参考这里在C#中调用phantomjs抓取网页。
2.新建一个js文件命名为xiaomi.js,内容如下
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 35 36 37 38 39 40 41 42 43 44 45 46 |
var page = require('webpage').create(), testindex = 0, loadInProgress = false; page.onLoadStarted = function() { loadInProgress = true; console.log("load started"); }; page.onLoadFinished = function() { loadInProgress = false; console.log("load finished"); }; var steps = [ function() { page.open("https://account.xiaomi.com/pass/serviceLogin"); }, function() { page.evaluate(function(obj) { var form = document.getElementById("login-main-form"); form.elements["username"].value = '用户名'; form.elements["pwd"].value = '密码'; form.elements['login-button'].click(); return document.title; }); loadInProgress = true; }, function() { page.render('login-succ-xiaomi.png'); } ]; var interval = setInterval(function() { if (!loadInProgress && typeof steps[testindex] == "function") { steps[testindex](); testindex++; } if (typeof steps[testindex] != "function") { phantom.exit(); } }, 10); |
3.C#工程代码如下。点击运行,控制台界面出现约3s左右,控制台会自动退出,这时在我们C#工程的Debug文件夹下回有一张名为“login-succ-xiaomi.png”的文件出现,这时我们自动登陆已经成功了。是不是so easy呢?
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 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NReco.PhantomJS; using System.IO; using System.Web.Script.Serialization; namespace phantomjsConsole { class Program { static void Main(string[] args) { var phantomJS = new PhantomJS(); try { phantomJS.Run("xiaomi.js",null); } finally { phantomJS.Abort(); // ensure that phantomjs.exe is stopped } } } } |
那么既然可以模拟登录小米商城,用这种方法应该也可以登陆其他不需要验证码的网站,自然而然我就想到了模拟登陆TB。目前TB登录时需要“拖动滑块”来验证,实现此功能需要在js文件中模拟鼠标拖动的动作,可惜本人js纯新手一枚,还暂未实现该功能。