selenium + firefox模拟登录qz

在网上看到的大部分都是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,才能定位元素

猜你喜欢

转载自www.cnblogs.com/tele-share/p/9582490.html