如何在XPath中返回直接父级并获取文本?

Ais*_*ish 3 java xml selenium xpath selenium-webdriver

我的xpath

//div[contains(@class,'ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable')]//div[@class='ui-widget-content slick-row odd' or @class='ui-widget-content slick-row even']/div/input[contains(@id,'custProglabel')]
Run Code Online (Sandbox Code Playgroud)

我需要divinputtag 之前访问并获取其文本.我试过用:

By.Xpath(//input[contains(@id,'custProglabel')]/preceding-sibling::div).getText();
Run Code Online (Sandbox Code Playgroud)

我有很多像这样的元素,只有输入标签的内容发生了变化.所以根据内容我试图访问直接div并获取其文本.

Guy*_*Guy 10

您可以立即使用父母 ..

By.xpath("//input[contains(@id,'custProglabel')]/..")
Run Code Online (Sandbox Code Playgroud)

作为旁注,xpath应以小写'x'开头.


kjh*_*hes 6

考虑使用谓词,而不是下降到input并返回到divdiv

//div[input/@id='custProglabel']
Run Code Online (Sandbox Code Playgroud)

或任何元素

//*[input/@id='custProglabel']
Run Code Online (Sandbox Code Playgroud)

另请注意,contains()可能会错误地匹配custProglabel2or MYcustProglabel,因此最好在此处使用相等测试。

  • 为什么选择具有子级 `//*[*/@id='id']` 的父级比选择子级 `//*[@id='id']/..` 的父级更好?有什么合理的理由吗? (3认同)