Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium使用Java-无法在Google搜索页面上找到Webelements_Java_Selenium - Fatal编程技术网

Selenium使用Java-无法在Google搜索页面上找到Webelements

Selenium使用Java-无法在Google搜索页面上找到Webelements,java,selenium,Java,Selenium,我想在谷歌主页上搜索Prime视频,然后我想点击谷歌搜索页面上的新闻链接。我使用了xpath来查找此链接,但在执行代码时,我没有得到任何TouchElementException。我使用了以下代码,请帮助我了解以下代码不起作用的原因: System.setProperty("webdriver.gecko.driver", "C:/Users/gecko/geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get(

我想在谷歌主页上搜索Prime视频,然后我想点击谷歌搜索页面上的新闻链接。我使用了xpath来查找此链接,但在执行代码时,我没有得到任何TouchElementException。我使用了以下代码,请帮助我了解以下代码不起作用的原因:

System.setProperty("webdriver.gecko.driver", "C:/Users/gecko/geckodriver.exe");

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com/");
WebElement ele = driver.findElement(By.name("q"));
ele.sendKeys("prime video");
ele.submit();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement news = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='hdtb-msb-vis']//div[text()='News']")));
    news.click();
    driver.close();

我使用的xpath略有不同:

WebElement news = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"hdtb-msb-vis\"]/div[2]/a")));

你能试试这个吗。我看到你忘了单击()也是。 Unlocate元素有几个原因。其中一个原因是xpath无效或未在该页上找到。检查的一种方法是使用find.element,然后使用xpath,如果找不到它,它将抛出异常。这里有一个例子

WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com/");
/*wait page for 2 seconds -- simple way wait, but don't recommended for using real testing*/
Thread.sleep(2000);
driver.findElement(By.name("q")).Click;
driver.sendKeys("prime video");
driver.sendKeys(Keys.ENTER);
然后尝试使用验证xpath是否有效

try
{   
   driver.findElement(By.xpath("//*[@id='hdtb-msb-vis']//div[text()='News']")).Click;
}
catch(NoSuchElementException ex)
{
   System.out.println("There is no element in this page or xpath is invalid : "+ex.Message);
 }
catch(Exception ex)
{
  System.out.println("Exception : "+ex.Message);
}
如果xpath无效或未找到,您可以尝试chrome的Katalon RecorderChropath扩展来帮助查找xpath

卡塔隆记录

Chropath