简体   繁体   中英

Selenium WebDriver C# - get text

I have this Html element on the page:

<li id="city" class="anketa_list-item">
   <div class="anketa_item-city">From</div>
    London
</li>

I found this element:

driver.FindElement(By.Id("city"))

If I try: driver.FindElement(By.Id("city")).Text , => my result: "From\r\nLondon".

How can I get only London by WebDriver?

You could easily get by using class-name :

driver.FindElement(By.Class("anketa_item-city")).Text;

or using Xpath

driver.FindElement(By.Xpath("\li\div")).Text;

Sorry for my misleading. My previous provide xpath is which ends in the function /text() which selects not a node, but the text of it.

Approach for this situation is get parent's text then replace children's text then trim to remove space/special space/etc ....

var parent = driver.FindElement(By.XPath("//li"))
var child = driver.FindElement(By.XPath("//li/div"))
var london = parent.Text.Replace(child.Text, "").Trim()

Notes:

If Trim() isn't working then it would appear that the "spaces" aren't spaces but some other non printing character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:

char[] charsToTrim = { ' ', '\t' };
string result = txt.Trim(charsToTrim);

You can try this:

var fromCityTxt = driver.FindElement(By.Id("city")).Text;
var city = Regex.Split(fromCityTxt, "\r\n")[1];

This worked for me.

driver.FindElement(By.XPath("//li[@id='city']/text()")); 在此处输入图像描述

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