问题
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?
回答1:
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;
回答2:
You can try this:
var fromCityTxt = driver.FindElement(By.Id("city")).Text;
var city = Regex.Split(fromCityTxt, "\r\n")[1];
回答3:
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);
来源:https://stackoverflow.com/questions/24690971/selenium-webdriver-c-sharp-get-text