Reputation: 101
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?
Upvotes: 8
Views: 71003
Reputation: 202
This worked for me.
driver.FindElement(By.XPath("//li[@id='city']/text()"));
Upvotes: 0
Reputation: 1320
You can try this:
var fromCityTxt = driver.FindElement(By.Id("city")).Text;
var city = Regex.Split(fromCityTxt, "\r\n")[1];
Upvotes: 1
Reputation: 497
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;
Upvotes: 14
Reputation: 1570
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);
Upvotes: 0