使用不同的定位器定位 WebElement(NoSuchElementException)

Locating WebElement using different locators(NoSuchElementException)

我在使用不同的定位器定位 WebElement 时遇到问题。在下面的 html 标签中,我尝试使用 linkTextxpathclassname 等不同的定位器定位 "write a review" WebElement 但仍然得到 NoSuchElementException

-->url https://www.tripadvisor.in/-->search for Club Mahindra-->click on Club Mahindra-->click on write a review.

    <a href="/UserReview-g641714-d1156207-Club_Mahindra_Madikeri_Coorg- 
    Madikeri_Kodagu_Coorg_Karnataka.html" target="_blank" class="ui_button 
    primary">Write a review</a>

使用的定位器

我真的很困惑。我做错了什么?

你可以试试

  //a[contains(text(),'Write a review')]

我已经厌倦了分析和实施。以下是我的发现:

-> 应用程序等待时间更长,因为有很多适用于页面的动态负载。

-> 需要实施适当的等待

-> 检查是否所有页面都在同一个选项卡中打开,或者单击每个 link 是否重定向到新选项卡,如果是这样,那么我们必须切换到特定的 window。

-> 下面的代码对我来说很专业。

    driver.get("https://www.tripadvisor.in/");
    WebDriverWait wait = new WebDriverWait(driver, 120);
    WebElement ele1 =  
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Where to?']")));
    ele1.click();

    WebElement ele2= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@placeholder='Where to?']")));
    ele2.sendKeys("club mahindra, india");

    WebElement ele3= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Search for ')]")));
    ele3.click();
    WebElement ele4= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Club Mahindra Madikeri, Coorg')]")));
    ele4.click();   //this click leads to a new tab 

    Set<String> winHandles = driver.getWindowHandles();  

    for(String str : winHandles) {
        driver.switchTo().window(str);
    }
    System.out.println(driver.getTitle());

    WebElement ele;
    int i=1;
    while(true) {
        try {
         ele = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Write a review']")));
         break;
        }catch(Exception e) {
            System.out.print(i++);
        }
    }
    System.out.println();
    Actions action = new Actions(driver);
    action.moveToElement(ele);
    ele.click();
    System.out.println("Clicked on the 'Write a review button'");