包含“9”的元素的 XPath 是什么?

问题描述 投票:0回答:2

从“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"));
  1. //div[contains(@class,'callout')]/descendant::text()[contains(., '9')]

  2. //div[contains(@class, 'callout')]//text()[contains(normalize-space(.), '9')]

  3. //div[contains(@class,'callout')]//text()[contains(., '9')]

下面的这个在两者中都不起作用(Chrome“通过 xpath 查找”/自动化脚本)

//div[contains(@class, 'callout')]//*[contains(text(), '9')]
c# selenium-webdriver xpath ui-automation
2个回答
0
投票

你可以试试这个:

//div[@class='callout' and contains(text(), '09')]

0
投票

你不能使用 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
© www.soinside.com 2019 - 2024. All rights reserved.