本文转载:通通学--知识学习与分享平台
转载链接:http://www.tongtongxue.com/archives/180.html
写过爬虫程序的码农都知道,实现爬虫程序登录的方法有多种,我这利用Selenium来实现登录。提供源代码下载
本案例实现登录的网站是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"); } }
其中源代码下载:源代码
其中Google浏览器驱动软件:chromedriver