英文:
What will be an XPath of element containing "9"?
问题
//div[contains(@class, 'callout')]//*[contains(text(), '9')]
英文:
What will be a correct XPath for locating "9" from line "09 Some text"?
<div class="callout" data-testid="callout" xpath="1">
<span class="container" data-testid="callout" xpath="1">
</span>
<p xpath="1">"Some text"</p>
"Some text1"
"09 Some text"
"Some text3"
</div>
I've tried the 3 locators below and I can locate element "9" from Chrome "Find by XPath" but when I use these in an automation script (Selenium WebDriver, C#m and specflow), they don't work.
IsElementDisplayed(By.XPath("xpath below"));
-
//div[contains(@class,'callout')]/descendant::text()[contains(., '9')]
-
//div[contains(@class, 'callout')]//text()[contains(normalize-space(.), '9')]
-
//div[contains(@class,'callout')]//text()[contains(., '9')]
This one below doesnt work in both (Chrome "Find by xpath" / automation script)
//div[contains(@class, 'callout')]//*[contains(text(), '9')]
答案1
得分: 2
// 你可以使用XPath来仅返回Selenium中的字符串/文本。例如,如果你使用以下XPath:
//div[@class='callout']/text()
它会抛出异常:
Exception has occurred: InvalidSelectorException
Message: invalid selector: The result of the xpath expression "//div[@class='callout']/text()" is: [object Text]. It should be an element.
你可以使用CSS选择器来实现:
div.callout
它会返回DIV内的整个文本块:
"\"Some text\"\r\n\"Some text1\" \"09 Some text\" \"Some text3\""
然后你可以解析出你想要的行:
string allText = driver.FindElement(By.CssSelector("div.callout")).Text;
string text = allText.Split('"').Where(w => w.StartsWith("09")).ToArray().First();
Console.WriteLine(text);
这会输出:
09 Some text
英文:
You can't use an XPath to return just a string/text in Selenium. For example, if you use the XPath
//div[@class='callout']/text()
it throws
Exception has occurred: InvalidSelectorException
Message: invalid selector: The result of the xpath expression "//div[@class='callout']/text()" is: [object Text]. It should be an element.
You CAN use a CSS selector
div.callout
and it returns the entire block of text inside the DIV
"\"Some text\"\r\n\"Some text1\" \"09 Some text\" \"Some text3\""
Then you can parse that down to the line you want.
string allText = driver.FindElement(By.CssSelector("div.callout")).Text;
string text = allText.Split('"').Where(w => w.StartsWith("09")).ToArray().First();
Console.WriteLine(text);
which prints
09 Some text
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论