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

我想在 Google 主页上搜索 Prime Video,然后我想在 Google 搜索页面上点击新闻链接。我已经使用 xpath 找到了这个链接,但是在执行代码时,我得到了 NoSuchElementException。我使用了下面的代码,请帮助我知道为什么下面的代码不起作用::


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();


倚天杖
浏览 244回答 2
2回答

跃然一笑

你可以试试这个。我看到你忘了Click(); 也是。取消定位元素有几个原因。其中一个原因是 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 无效或未找到,您可以尝试使用 Katalon Recorder或Chropath扩展 chrome 来帮助查找 xpath。加泰罗尼亚纪录https://chrome.google.com/webstore/detail/katalon-recorder/ljdobmomdgdljniojadhoplhkpialdid色光https://chrome.google.com/webstore/detail/chropath/ljngjbnaijcbncmcnjfhigebomdlkcjo?hl=en

富国沪深

它适用于我的 xpath 略有不同:WebElement news = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"hdtb-msb-vis\"]/div[2]/a")));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java