簡體   English   中英

如何使用Selenium Webdriver處理Javascript單擊?

[英]How to handle Javascript click by using selenium Webdriver?

我正在使用Selenium Webdiver。 我的測試用例是。

  1. 登錄到站點。
  2. 點擊通知鏈接。

點擊通知鏈接時遇到問題,其HTML代碼如下:-

<ul class="rghtSec fr menu logged"><li><a href="javascript:;">
  <div class="topIcon notify"><span>&nbsp;</span></div>
  <div class="mTxt">Notifications<span id="rJobCntr" class="rJobCntr"></span></div></a>
  <div class="subMenu recommendTT">
    <ul>
      <li><a target="_blank" class="blob" id="blobId" href="http://jobsearch.naukri.com/notifications">
Fetching jobs you may apply for</a></li>
    </ul>

我嘗試了以下5種不同的方式:

/*1*/ driver.findElement(By.xpath("//a[@class='mTxt']")).click();

/*2*/ driver.findElement(By.cssSelector("div[class='topIcon notify']")).click();

/*3*/ driver.findElement(By.linkText("Notifications")).click();

/*4*/ driver.findElement(By.xpath("//div[@class='pNotifyCont dspN']")).click();

/*5*/ Actions mouse=new Actions(driver);
   WebElement element=driver.findElement(By.xpath("//div[@class='pNotifyCont dspN']"));
   mouse.moveToElement(element).click().build().perform();

Error : Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//a[@class='mTxt']"} Command duration or timeout: 7.56 seconds

但是這些方法都不能解決問題:(,誰能幫我解決這個問題嗎?

請替換您的xpath表達式為

driver.findElement(By.xpath("//div[contains(text(),'Notifications')]")).click();

Notifications位於div標簽中。

如果要選擇此“ Notifications鏈接下的元素,可以按照以下xpath進行操作:

driver.findElement(By.xpath("//div[contains(text(),'Notifications')]/following::a[1]")).click();

您可以根據href屬性的值直接單擊鏈接:

driver.findElement(By.cssSelector("a[href*='notifications']")).click();

要么

driver.findElement(By.cssSelector("a[href=\"http://jobsearch.naukri.com/notifications\"]")).click();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM