抓百度指数之类数据的时候需要登陆获取cookie,本文章介绍两种基于无头浏览器的方式模拟登录百度,获取cookie的方式。
casperjs代码
var casper = require('casper').create();
casper.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0');
casper.start('https://passport.baidu.com/v2/?login', function() {
this.fill('form[id="TANGRAM__PSP_3__form"]', {
'userName' : '填入账号',
'password' : '填入密码'
}, false); // false不立即提交表单,这边设置成true的话,会弹出验证码,必须false
});
casper.then(function() {
// 点击事件
this.click('input[id="TANGRAM__PSP_3__submit"]');
this.echo('login...');
});
casper.then(function() {
this.wait(3000, function() {
this.capture("baidu.png");
});
});
casper.run();
截图可以看到登陆后的首页。
另外一个无头浏览器htmlunit写法
maven依赖,就一个。
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.44.0</version>
</dependency>
package com.hyh.casperjs.demo;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
public class BaiduCookie {
/**
* 获取百度cookie
*/
public static String getSinaCookie(String username, String password)
throws Exception {
StringBuilder sb = new StringBuilder();
HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);
driver.get("https://passport.baidu.com/v2/?login");
WebElement userName = driver
.findElementByCssSelector("input[id=TANGRAM__PSP_3__userName]");
userName.sendKeys(username);
WebElement pass = driver
.findElementByCssSelector("input[id=TANGRAM__PSP_3__password]");
pass.sendKeys(password);
WebElement submit = driver
.findElementByCssSelector("input[id=TANGRAM__PSP_3__submit]");
submit.click();
Set<Cookie> cookieSet = driver.manage().getCookies();
driver.close();
for (Cookie cookie : cookieSet) {
sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
}
String cookie = sb.toString();
System.out.println(cookie);
return cookie;
}
/**
* 看看能不能访问登录之后跳转的主页
*
* 这边只是做个测试代码,懒得使用HttpClient,HttpURLConnection去抓了,为什么不使用上面那个HtmlUnitDriver类,
* 因为我随便百度到WebClient设置cookie,所以懒得再去百度下HtmlUnitDriver如何设置cookie。
*
* 大家可以根据自己需要去选择相应的jar包来抓取网页,只要设置好cookie之类的头参数就行了。
*/
public static void test(String cookie) {
URL link = null;
try {
link = new URL("https://passport.baidu.com/center?_t=1439976374");
} catch (MalformedURLException e) {
e.printStackTrace();
}
WebClient wc = new WebClient();
WebRequest request = new WebRequest(link);
// 重要的步骤
request.setAdditionalHeader("Cookie", cookie);
request.setCharset("UTF-8");
// request.setProxyHost("120.120.120.x");
// request.setProxyPort(8080);
// 设置请求报文头里的refer字段
// request.setAdditionalHeader("Referer", refer);
request.setAdditionalHeader("User-Agent",
"Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
// wc.addRequestHeader和request.setAdditionalHeader功能应该是一样的。选择一个即可。
// 其他报文头字段可以根据需要添加
// 开启cookie管理
wc.getCookieManager().setCookiesEnabled(true);
// 开启js解析。对于变态网页,这个是必须的
wc.getOptions().setJavaScriptEnabled(true);
// 开启css解析。对于变态网页,这个是必须的
wc.getOptions().setCssEnabled(true);
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
wc.getOptions().setThrowExceptionOnScriptError(false);
wc.getOptions().setTimeout(10000);
// 打印html内容
try {
System.out.println(wc.getPage(request).getWebResponse()
.getContentAsString());
} catch (FailingHttpStatusCodeException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
// 这边填入百度的账号和密码
String cookie = getSinaCookie("username", "password");
test(cookie);
}
}