【问题标题】:How to click an svg element in selenium webdriver如何在 selenium webdriver 中单击 svg 元素
【发布时间】:2020-12-22 03:15:35
【问题描述】:

我有一个 svg 对象,使用 Selenium webdriver,我需要单击按钮并转到上一页。使用 xpath 我无法这样做。 下面是 svg 的 html 代码,但我无法获取相同的 xpath。非常感谢任何帮助。

HTML 代码:

<div class="title-holder">
   <h4>Home Dashboard</h4>
   <div class="time">3:48pm ET</div>
   <button class="update-button" type="button" data-testid="header-update-link" title="Refresh">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
      <path fill="currentColor" d="M20 12l-2.5 3-.18-.22-.71-.84L15 12h2a5.007 5.007 0 0 0-8.49- 
      3.59l-.63-.76A5.9083 5.9083 0 0 1 12 6c3.3137 0 6 2.6863 6 6h2zm-4.51 3.59A5.007 5.007 0 0 1 7 
      12h2l-1.61-1.93v-.01l-.71-.84L6.5 9 4 12h2c0 3.3137 2.6863 6 6 6a5.9083 5.9083 0 0 0 4.12- 
      1.65l-.63-.76z"></path>
    </svg>
   </button>
</div>

【问题讨论】:

  • 尝试使用 Actions 类,如下所示。它通过了测试但不执行点击操作。 WebElement svgObject = webDriver.findElement(By.xpath("//*[name()='svg']")); Actions builder = new Actions(webDriver); builder.click(svgObject).build().perform();

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

Xpath:

//*[@class='update-button']/*[name()='svg']

尝试 javascript 来执行点击操作

WebElement ele = driver.findElement(By.xpath("//*[@class='update-button']/*[name()='svg']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", ele);

【讨论】:

  • 它说 org.openqa.selenium.JavascriptException: javascript error: arguments[0].click is not a function
【解决方案2】:

根据您共享的 HTML,您可以安全地避开 &lt;svg&gt; 元素并单击父 &lt;button&gt; 元素诱导 WebDriverWait 以获取 elementToBeClickable(),您可以使用以下任一 Locator Strategies

  • cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.update-button[data-testid='header-update-link'][title='Refresh']"))).click();
    
  • xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='update-button' and @data-testid='header-update-link'][@title='Refresh']"))).click();
    

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 2017-06-09
    • 1970-01-01
    • 2016-10-03
    • 2017-12-02
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多