网络爬虫:利用Selenium实现登录

来源:互联网 发布:组态软件 电力行业 编辑:程序博客网 时间:2024/05/16 05:39

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

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

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

以下是关键代码:

程序启动类:WebSpider.java

[java] view plain copy print?
  1. package com.tongtongxue.webspider;  
  2.   
  3. import com.tongtongxue.webspider.fetcher.Fetcher;  
  4.   
  5. public class WebSpider {  
  6.   
  7.     public static void main(String[] args) throws Exception {  
  8.         Fetcher fetcher = new Fetcher();  
  9.         fetcher.fetch();  
  10.     }  
  11. }  



抓取类:Fetcher.java

[java] view plain copy print?
  1. package com.tongtongxue.webspider.fetcher;  
  2.   
  3. import java.util.concurrent.TimeUnit;  
  4.   
  5. import org.openqa.selenium.By;  
  6. import org.openqa.selenium.WebDriver;  
  7. import org.openqa.selenium.chrome.ChromeDriver;  
  8.   
  9. import com.thoughtworks.selenium.Selenium;  
  10. import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;  
  11.   
  12.   
  13. public class Fetcher {  
  14.     private WebDriver webDriver;  
  15.     private Selenium selenium;  
  16.   
  17.     // 第三方的登录工具的用户名,我这里用的是新浪微博  
  18.     private String username = "xxxxxx";  
  19.     // 第三方的登录工具的密码,我这里用的是新浪微博  
  20.     private String password = "xxxxxx";  
  21.   
  22.     public Fetcher() throws Exception {  
  23.         // 设置google浏览器的驱动位置  
  24.         System.setProperty("webdriver.chrome.driver" , "E:/it_jar_file/chromedriver_win32/chromedriver.exe");  
  25.         webDriver = new ChromeDriver();  
  26.         webDriver.manage().timeouts().pageLoadTimeout(12000, TimeUnit.SECONDS);  
  27.         selenium = new WebDriverBackedSelenium(webDriver, "http://www.iteye.com");  
  28.         selenium.setTimeout("120000");  
  29.     }  
  30.   
  31.     public void fetch() throws Exception {  
  32.         // 这是入口网址  
  33.         webDriver.get("http://www.iteye.com/login");  
  34.         waitForPageToLoad();  
  35.   
  36.         // 选择第三方登录工具  
  37.         selenium.click("css=div.third a[href='/auth/weibo']");  
  38.         waitForPageToLoad();  
  39.   
  40.         // 输入用户名  
  41.         webDriver.findElement(By.id("userId")).sendKeys(username);  
  42.         // 输入密码  
  43.         webDriver.findElement(By.id("passwd")).sendKeys(password);  
  44.   
  45.         Thread.sleep(2000);  
  46.   
  47.         // 点击登录按钮  
  48.         selenium.click("css=p.oauth_formbtn a[node-type='submit']");  
  49.     }  
  50.   
  51.     private void waitForPageToLoad() {  
  52.         selenium.waitForPageToLoad("120000");  
  53.     }  
  54. }  

原创粉丝点击