我需要 Selenium JavascriptExecutor 通过 jquery 返回一个元素 [英] I need Selenium JavascriptExecutor to return an element via jquery
问题描述
我对此不知所措,我确信答案很简单,但我就是想不通.
I am at my wits end with this and I'm sure the answer is simple but I just can't figure it out.
我有一个 jquery 选择器,当我把它放在谷歌浏览器的控制台中时,它可以完美地找到和元素:
I've got a jquery selector that finds and element perfectly when I put this in the console of google Chrome:
$(".answer__label:contains('Yes')")
现在我想用它来检索 WebDriver 测试中的一个元素,所以我以下列方式使用 JavascriptExecutor:
Now I want to use this to retrieve an element in a WebDriver test, so I'm using JavascriptExecutor in the following way:
private WebElement findByJSText(String text) {
String script = String.format("return ('.answer__label:contains('%s')')", text);
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript(script);
return element;
}
这给出了错误,括号中缺少 )".我到处都看到了对这个错误的引用,但似乎没有一个适用于我的情况.
This gives the error, "missing ) in parenthetical". I've seen references to this error all over, but none that seem to apply to my situation.
我如何按摩它以正确返回元素?
How do I massage this to return the element properly?
(请不要回复告诉我使用 driver.findElement(By.linkText),谢谢)
(please don't respond telling me to use driver.findElement(By.linkText), thanks)
附录
这是我最终的工作方法:
Here's what my final working method looks like:
private WebElement findByJSText(String text) {
//String script = String.format("return $('.answer__label:contains('%s')')", text);
String script = String.format("return $(\".answer__label:contains('%s')\")[0]", text);
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript(script);
return element;
}
我可以为 css 字符串添加第二个参数以使其更灵活.
I may add a 2nd parameter for a css string to make this more flexible.
感谢大家的帮助!
推荐答案
在这一行:
String script = String.format("return ('.answer__label:contains('%s')')", text);
你的javascript代码出错了,jquery的$
函数在哪里?正确的js代码应该是:
Your javascript code is error, where is the jquery $
function? Correct js code should be:
String script = String.format("return $('.answer__label:contains('%s')')", text);
您在另一个 '
中有 '
.这就是问题所在,我尝试了以下 js 代码并且对我来说效果很好:
You have the '
within another '
. Thats the problem, I tried the following js code and its working fine for me:
String script = String.format("return $(\".answer__label:contains('%s')\")", text);
这篇关于我需要 Selenium JavascriptExecutor 通过 jquery 返回一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!