java 如何回到 XPath 中的直接父级并获取文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36606901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:40:19  来源:igfitidea点击:

How to go back to the immediate parent in XPath and get the text?

javaxmlseleniumselenium-webdriverxpath

提问by Aish

My xpathis

我的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')]

I need to access divjust before inputtag and get its text. I tried using:

我需要divinput标记之前访问并获取其文本。我尝试使用:

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

I have many elements like this and only the content of my input tag changes. So based on the content I am trying to access the immediate div and get its text.

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

回答by Guy

You can get immediate parent using ..

您可以使用直接父母 ..

By.xpath("//input[contains(@id,'custProglabel')]/..")

As a side note, xpathshould start with lower case 'x'.

作为旁注,xpath应以小写“x”开头。

回答by kjhughes

Rather than drop down to inputand come back up to div, consider using a predicate on div

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

//div[input/@id='custProglabel']

or any element

或任何元素

//*[input/@id='custProglabel']

Also, note that contains()could mistakenly match custProglabel2or MYcustProglabel, so it's better to use equality test here.

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

回答by Sadik Ali

use below xpath:

使用下面的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')]/parent::div