简体   繁体   中英

Get Text from SVG selenium java

I am uable to getText from Text tag in SVG. I am Attaching HTML

<svg width="553" height="200" style="overflow: hidden;" aria-label="A chart.">
     <defs id="defs">
     <rect x="0" y="0" width="553" height="200" stroke="none" stroke-width="0" fill="#ffffff">
     <g>
         <text text-anchor="start" x="77" y="22.85" font-family="Arial" font-size="11" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">Clustering done on Mar 30, 2017 11:13 AM</text>
         <rect x="77" y="13.5" width="400" height="11" stroke="none" stroke-width="0" fill-opacity="0" fill="#ffffff">
     </g>

The get I want to get is Clustering done on Mar 30, 2017 11:13 AM

driver.findElement(By.xpath("//*[local-name='svg']//*[local-name='g']//*[local-name='text']")).getText();

This will definitely work: 1- driver.findElement(By.xpath("WriteXpathHere")).getAttribute("innerHTML"));

OR

2- driver.findElement(By.xpath("WriteXpathHere")).getAttribute("textContent"));

Note: Even if there is no attribute by the name "innerHTML" or "TextContent" this will work. Just copy this and only insert the Xpath

For reference: https://gist.github.com/sajithatharaka/37c33008e68f1649281790a103adc60c

This locator should work:

  • String text=driver.findElement(By.xpath("//[@id='divClusters']//*[name()='svg' and @aria-label='A chart.']//*[name()='g']")).getText(‌​); System.out.print(text);

Explanation:

  • .//div - remove . to search the whole document, not just in currently selected context element
  • remove absolute /div[1]/.. divs reference since it's not reliable
  • refer to svg element as //*[name()='svg']
  • add some meaningful attribute @aria-label='A chart.' to svg element
  • Elements inside svg should be handled in the same way: //*[name()="g"], //*[name()="defs"] - thanks to Andersson for clarifying this.

试试下面:

driver.findElement(By.cssSelector("#divClusters svg > g‌ > text")).getText();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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