---
title: "网络爬虫：利用Selenium实现登录"
author: "芝加哥09"
date: "2015-11-15T21:55:08Z"
tags: ["网络爬虫"]
categories: ["开源软件"]
slug: "selenium"
draft: false
lastmod: "2015-11-15T22:03:29Z"
id: 2256958
url: "https://09094224.iteye.com/blog/2256958"
---

**本文转载：**[通通学--知识学习与分享平台](http://www.tongtongxue.com)

**转载链接：**http://www.tongtongxue.com/archives/180.html

 

写过爬虫程序的码农都知道，实现爬虫程序登录的方法有多种，我这利用Selenium来实现登录。**提供源代码下载**

 

**![](http://dl2.iteye.com/upload/attachment/0113/0786/94f071a3-17e2-3f63-8bc4-69e90409451b.jpg)**  
 

本案例实现登录的网站是iteye，同时登录时选择第三方登录工具，本处利用的新浪微博来登录。

 

以下是关键代码：

 

**程序启动类：WebSpider.java**

 

```
package com.tongtongxue.webspider;

import com.tongtongxue.webspider.fetcher.Fetcher;

public class WebSpider {

    public static void main(String[] args) throws Exception {
        Fetcher fetcher = new Fetcher();
        fetcher.fetch();
    }
}
```

 

**抓取类：Fetcher.java**

 

```
package com.tongtongxue.webspider.fetcher;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;


public class Fetcher {
    private WebDriver webDriver;
    private Selenium selenium;

    // 第三方的登录工具的用户名，我这里用的是新浪微博
    private String username = "xxxxxx";
    // 第三方的登录工具的密码，我这里用的是新浪微博
    private String password = "xxxxxx";

    public Fetcher() throws Exception {
        // 设置google浏览器的驱动位置
        System.setProperty("webdriver.chrome.driver" , "E:/it_jar_file/chromedriver_win32/chromedriver.exe");
        webDriver = new ChromeDriver();
        webDriver.manage().timeouts().pageLoadTimeout(12000, TimeUnit.SECONDS);
        selenium = new WebDriverBackedSelenium(webDriver, "http://www.iteye.com");
        selenium.setTimeout("120000");
    }

    public void fetch() throws Exception {
        // 这是入口网址
        webDriver.get("http://www.iteye.com/login");
        waitForPageToLoad();

        // 选择第三方登录工具
        selenium.click("css=div.third a[href='/auth/weibo']");
        waitForPageToLoad();

        // 输入用户名
        webDriver.findElement(By.id("userId")).sendKeys(username);
        // 输入密码
        webDriver.findElement(By.id("passwd")).sendKeys(password);

        Thread.sleep(2000);

        // 点击登录按钮
        selenium.click("css=p.oauth_formbtn a[node-type='submit']");
    }

    private void waitForPageToLoad() {
        selenium.waitForPageToLoad("120000");
    }
}
```

 

其中源代码下载：[源代码](http://pan.baidu.com/s/1sj7pxTF)

其中Google浏览器驱动软件：[chromedriver](http://pan.baidu.com/s/1jGD9q0e)