Java 我们如何将变量(字符串)传递给 xpath 包含函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34331795/
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-08-11 15:32:45  来源:igfitidea点击:

How can we pass a variable( string) to an xpath contains function?

javaseleniumxpath

提问by Resmi

I need to find an element that contains a particular text. How can I do that without hardcoding the text. How can I make the text a variable and pass it to the xpathfunction?

我需要找到一个包含特定文本的元素。如果不对文本进行硬编码,我该如何做到这一点。如何使文本成为变量并将其传递给xpath函数?

public static void selectEvent(String eventName) { 

WebElement eventLink = Browser.instance.findElement(By.xpath("//td[2]/a[1][contains(text(), 'Birthday Party')]")); 
eventLink.click(); 
} 

Here instead of using the text Birthday PartyI need to use the parameter eventNamethat has been passed to the method.

在这里,我需要使用已传递给该方法的参数eventName,而不是使用文本Birthday Party

采纳答案by Bharat DEVre

If you are using java then declare a method which returns particular element,

如果您使用的是 java,则声明一个返回特定元素的方法,

public WebElement getElementByXpathContainsText(String xpath)
    {
    return webDriver.findElement(By.ByXPath(xpath));
    }

Just call getElementByXpathContainsText() by passing any xpath as parameter.

只需通过传递任何 xpath 作为参数来调用 getElementByXpathContainsText() 。

for your code try following way,

对于您的代码,请尝试以下方式,

public static void selectEvent(String eventName) { 
WebElement eventLink = Browser.instance.findElement(By.xpath("//td[2]/a[1][contains(text(), '"+eventName+"')]")); eventLink.click(); 
}