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

huangapple go评论57阅读模式
英文:

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>

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

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"));
  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')]

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

huangapple
  • 本文由 发表于 2023年4月11日 11:53:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定