在一些爬虫中,需要用到账号登录进入,才能看到需要爬取的内容,因此实现程序自动模拟登录非常有必要。
目前大部分网站的登录,都是使用表单提交的方法实现的,这一类网站的模拟登录,相信度娘已经给出来的许多实例。还有一类网站不是使用网页自带表单提交的方法,网站自己实现了js方法来登录,这就需要进行特别的模拟浏览器行为。
本文用到的主要技术手段包括Selenium+Phantomjs+Jsoup。
WebDriver
/**
* @DESC 获取PhantomJSDriver
* @param phantomJS
* @return WebDriver
*/
public static WebDriver getPhantomJs(String phantomJS) {
System.setProperty("phantomjs.binary.path", phantomJS);
DesiredCapabilities desiredCapabilities = DesiredCapabilities
.phantomjs();
desiredCapabilities.setJavascriptEnabled(true);
String headers = getHeaders();// 生成随机User_Agent
desiredCapabilities.setCapability("phantomjs.page.settings.userAgent",
headers);
desiredCapabilities.setCapability(
"phantomjs.page.customHeaders.User-Agent", headers);
PhantomJSDriver driver = new PhantomJSDriver(desiredCapabilities);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
return driver;
}
模拟登录
public static void main(String[] args) throws IOException {
WebDriver wd = getPhantomJs("Your Phantomjs Path");
wd.get("Target Website");
wd.findElement(By.id("txtUserName")).sendKeys(
"Your Account");
wd.findElement(By.id("txtPassword")).sendKeys("Your Passwd");
JavascriptExecutor js = (JavascriptExecutor) wd;
js.executeScript("网站登录方法[一般会在JS中找到,或触发,或点击]");
try {// 等待登录加载完成
Thread.sleep(PAUSE_TIME);
} catch (InterruptedException e) {
}
Set<Cookie> coks = wd.manage().getCookies();
wd.quit();
// 保存登录的Cookies
Map<String, String> cookies = new HashMap<String, String>();
for (Cookie ck : coks)
cookies.put(ck.getName(), ck.getValue());
}