简体   繁体   中英

How to extract partial text from an element seperated by <br> tag through selenium?

How to separate 70 from 70 (100%) where 70 and (100%) are linked by <br> tag in selenium?

Here's the structure:

<a href="/report/campaigns/698/sent" class=""> 70<br> (100%)</a>

Code that I am using is :

String[] REP=new String[1];
String Repor= driver.findElement(By.xpath("//html[1]/body[1]/section[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[5]/table[1]/tbody[1]/tr[1]/td[6]")).getText();

REP=Repor.split(""); 

System.out.println("REP "+REP[0]);

Output that i am getting is : 7

That Xpath is crazy, but to address your issue I think it might be as simple as adding a space between the quotes in your split() function. It should be

REP=Repor.split(“ “)

Edit after clarification: the string Repor is being set with a line break. Thus the following code should find "70" and "(100%)" individually.

String lines[] = Repor.split("\\r?\\n");

then lines[0] is "70" and lines[1] is "(100%)". Is this what you wanted?

To extract the text 70 you can use either of the following Locator Strategies :

  • cssSelector :

     WebElement myElement = driver.findElement(By.cssSelector("a[href='/report/campaigns/698/sent']")); String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].firstChild.textContent;', myElement).toString(); 
  • xpath :

     WebElement myElement = driver.findElement(By.xpath("//a[@href='/report/campaigns/698/sent']")); String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].firstChild.textContent;', myElement).toString(); 

每个标签都被视为父标签存在的文本节点的分隔符:决定是指定所需文本节点的索引//a/text()[1]

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