【问题标题】:How do I find an element with xpath?如何使用 xpath 找到元素?
【发布时间】:2021-04-17 09:21:38
【问题描述】:

我试图找到一个“按钮”并单击它,但它没有 id。 我尝试使用 Xpath 甚至 cssSelector 但没有任何效果。

这是按钮的元素:

div style="cursor: grabbing;" title="Approved Forms" onclick="goToForms(0)" class="col-lg-2 col-sm-6"

我试过这个:

driver.findElement(By.xpath("//div[contains(@title=,'Approved Forms')]")).click();
driver.findElement(By.xpath("/html/body/div[3]/div/div/div[2]/div[1]")).click(); *copy xpath*
driver.findElement(By.cssSelector(['title="Approved Forms"'])).click(); *has a sintax errors, not sure how to write it*

【问题讨论】:

标签: java selenium selenium-webdriver selenium-chromedriver selenium-ide


【解决方案1】:

要定位元素,您可以使用以下任一Locator Strategies

  • cssSelector:

    WebElement element = driver.findElement(By.cssSelector("div[title='Approved Forms'][onclick^='goToForms']"));
    
  • xpath:

    WebElement element = driver.findElement(By.xpath("//div[@title='Approved Forms' and starts-with(@onclick, 'goToForms')]"));
    

理想情况下,您需要为visibilityOfElementLocated() 诱导WebDriverWait,并且可以使用以下任一定位器策略

  • cssSelector:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[title='Approved Forms'][onclick^='goToForms']")));
    
  • xpath:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@title='Approved Forms' and starts-with(@onclick, 'goToForms')]")));
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多