简体   繁体   English

如何在 selenium webdriver 中点击一个 svg 元素

[英]How to click an svg element in selenium webdriver

I have an svg object, using Selenium webdriver, I need to click as a button and go to previous page.我有一个 svg object,使用 Selenium webdriver,我需要点击按钮和 go 到上一页。 Using xpath I am unable to do so.使用 xpath 我无法这样做。 Below is the html code for svg but I am unable to fetch the xpath for the same.下面是 svg 的 html 代码,但我无法获取相同的 xpath。 Any help is highly appreciated.非常感谢任何帮助。

HTML Code: 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>

Xpath: Xpath:

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

Try javascript to perform click action试试javascript执行点击动作

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

As per the HTML you have shared, you can safely avoid the <svg> element and click on the parent <button> element inducing WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies :根据您共享的 HTML,您可以安全地避开<svg>元素并单击父<button>元素,为elementToBeClickable()诱导WebDriverWait并且您可以使用以下任一定位器策略

  • cssSelector : cssSelector

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM