面对" org.openqa.selenium.ElementNotVisibleException:元素不可见"虽然我能够在DoM结构中通过xpath定位元素。但是显式和隐含的等待仍然会继续。
package google;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Trail {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","F:\\Automation\\Software\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
// Opening URL
driver.get("https://www.google.co.in/");
driver.manage().window().maximize();
driver.findElement(By.xpath("//input[@type='text' and @id='lst-ib']")).sendKeys("pineapple");
Thread.sleep(1000);
//giving input and clicking on search
WebElement ele = driver.findElement(By.xpath("//input[@name=\"btnK\"]"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
driver.findElement(By.xpath("//input[@name=\"btnK\"]")).click();
// Trying to click the first link available
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/*[@id=\"rso\"]/div[1]/div/div[1]/div/div/h3/child::*")));
element.click();
/* WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/*[@id=\"rso\"]/div[1]/div/div[1]/div/div/h3/child::*")));
element.click();*/
}
}
答案 0 :(得分:0)
要从 Google搜索结果中提供的第一个链接上click()
,您必须引导 WebDriverWait 以及 ExpectedConditions 子句集到 elementToBeClickable ,您可以使用以下代码块:
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.com/");
WebElement search_field = driver.findElement(By.name("q"));
search_field.sendKeys("pineapple");
search_field.submit();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='rso']//div[@class='g']//h3/a"))).click();
System.out.println("Page Title is : "+driver.getTitle());
driver.quit();
控制台输出:
Page Title is : Pineapple: Health Benefits, Recipes, Health Risks