亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

倚天杖 2022-06-30 18:29:41
我想在 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();
查看完整描述

2 回答

?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

你可以試試這個。我看到你忘了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


查看完整回答
反對 回復 2022-06-30
?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

它適用于我的 xpath 略有不同:

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



查看完整回答
反對 回復 2022-06-30
  • 2 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號