selenium + firefox模擬登錄qz
阿新 • • 發佈:2018-09-04
exce setprop efault int ref class binary size nbsp
在網上看到的大部分都是Python版本的,於是寫了個java版本的
環境:
selenium-java 3.9.1
firefox 57.0
geckodriver 0.19.1
firefox與geckodriver下載地址請參考https://blog.csdn.net/cyjs1988/article/details/73039423
代碼(註意修改用戶名與密碼)
1 public class QZLogin {
2
3 public static void main(String[] args) throws Exception {
4 System.setProperty("webdriver.gecko.driver", "D:/browserdriver/geckodriver.exe");
5
6 FirefoxOptions options = new FirefoxOptions();
7 options.setBinary("F:/ff/firefox.exe");
8
9 WebDriver driver = new FirefoxDriver(options);
10 driver.manage().window().maximize();
11 //超時
12 try {
13 driver.manage().timeouts().pageLoadTimeout(3,TimeUnit.SECONDS);
14 driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS);
15 driver.get("https://i.qq.com/");
16 } catch (Exception e) {
17 System.out.println("所需元素已出現,停止加載頁面");
18 }finally {
19 //切換到登錄login
20 driver.switchTo().frame("login_frame");
21
22 WebElement switcher_plogin = driver.findElement(By.id("switcher_plogin"));
23 System.out.println(switcher_plogin.getText());
24 if(switcher_plogin.isDisplayed()) {
25 switcher_plogin.click();
26 }
27 //用戶名
28 driver.findElement(By.id("u")).clear();
29 driver.findElement(By.id("u")).sendKeys("******");
30
31 //密碼
32 driver.findElement(By.id("p")).clear();
33 driver.findElement(By.id("p")).sendKeys("******");
34
35 //登錄
36 driver.findElement(By.id("login_button")).click();
37
38 //等待跳轉
39 Thread.sleep(3000);
40
41 //退出frame
42 driver.switchTo().defaultContent();
43
44 System.out.println(driver.getCurrentUrl());
45
46 }
47
48
49 // driver.quit();
50 }
如果你發現程序可以執行,但是速度極慢,多半是因為沒有設置超時,導致頁面一直在加載,事實上只要你定位的元素出現,就可以停止加載頁面了,涉及到iframe的必須切換到iframe,才能定位元素
selenium + firefox模擬登錄qz