selenium知识点

1.maven引入selenium jar包

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>

  

2. 元素等待

1)显式等待

WebDriver driver = new ChromeDriver();
driver.get("https://www.baidu.com");
WebElement element = (new WebDriverWait(driver,5)).until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));

上面第三条语句表示,在0-5s中去定位id为“kw”的元素,WebDriverWait默认每500ms就调用一次ExpectedCondition直到定位成功或者时间截止,ExpectedCondition的返回值要么为true要么为不为空的对象,在规定时间内若没有定位成功元素,则until()会抛出org.openqa.selenium.TimeoutException 。
2)隐式等待

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.baidu.com");
WebElement element1 = ((ChromeDriver) driver).findElementById("kw");
上面第一条语句表示,如果元素不是马上就能定位成功,则WebDriver会在5s时间内去搜索DOM定位元素,这个时间一旦设置后它的范围就是WebDriver的整个生命周期,如果在规定时间内没有定位成功,则会抛出org.openqa.selenium.NoSuchElementException。

【备注】显示和隐式最好不要混用,混用的话可能会造成不可预估的等待时间,比如说设置了隐式等待10s,显示等待15s,可能在20s后就会发生超时

原文地址:https://www.cnblogs.com/peak911/p/10641032.html