从“09 Some text”行定位“9”的正确 XPath 是什么?
<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>
我已经尝试了下面的 3 个定位器,我可以从 Chrome“通过 XPath 查找”中找到元素“9”,但是当我在自动化脚本(Selenium WebDriver、C#m 和 specflow)中使用它们时,它们不起作用。
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')]
下面的这个在两者中都不起作用(Chrome“通过 xpath 查找”/自动化脚本)
//div[contains(@class, 'callout')]//*[contains(text(), '9')]
你可以试试这个:
//div[@class='callout' and contains(text(), '09')]
你不能使用 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