在一些爬虫中,需要用到账号登录进入,才能看到需要爬取的内容,因此实现程序自动模拟登录非常有必要。

  目前大部分网站的登录,都是使用表单提交的方法实现的,这一类网站的模拟登录,相信度娘已经给出来的许多实例。还有一类网站不是使用网页自带表单提交的方法,网站自己实现了js方法来登录,这就需要进行特别的模拟浏览器行为。

  本文用到的主要技术手段包括Selenium+Phantomjs+Jsoup。

WebDriver

  这里我们使用Phantomjs最为浏览器驱动,下面的方式是实现传入Phantomjs路径获取WebDriver的方法。其中随机产生UserAgent、打开JS运行开关,并设置了20S的默认超时时间。

/**
* @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;
}

模拟登录

  这里主要是通过WebDriver访问网页,并在WebDriver上做一些实际的操作,例如查找网页元素、给网页元素赋值、运行相关的JS以及获取cookies等操作。

public static void main(String[] args) 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 coks = wd.manage().getCookies();
    wd.quit();

    // 保存登录的Cookies
    Map cookies = new HashMap();
    for (Cookie ck : coks)
    	cookies.put(ck.getName(), ck.getValue());

}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

文本分类 上一篇
我与汽车之家的三生三世 下一篇