如何在 Selenium 中使用 JQuery?

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

How to use JQuery in Selenium?

jqueryselenium

提问by huahsin68

I would like to use Selenium to click on the tab of a web where the tab was created dynamically using JQuery. There is one problem, since it was created dynamically and the tab got no ID tied to it (only class-ID provided), so I am running out of clue to click on it using Selenium.

我想使用 Selenium 单击使用 JQuery 动态创建该选项卡的 Web 选项卡。有一个问题,因为它是动态创建的,并且选项卡没有绑定 ID(仅提供了类 ID),所以我没有线索可以使用 Selenium 来单击它。

After googling for 2 weeks, I found out that it could be done using JQuery by injecting JQuery into Selenium and repackaging it so that it support JQuery API. But the problem now is I don't know how to trigger JQuery script in Selenium?

在谷歌搜索 2 周后,我发现可以通过将 JQuery 注入 Selenium 并重新打包以支持 JQuery API 来使用 JQuery 来完成。但是现在的问题是我不知道如何在 Selenium 中触发 JQuery 脚本?

Is there any resources out there or guideline on setting up JQuery in Selenium? How am I going to execute JQuery in Selenium?

是否有关于在 Selenium 中设置 JQuery 的任何资源或指南?我将如何在 Selenium 中执行 JQuery?

采纳答案by Nthalk

You can try using my selenium lib at github.

您可以尝试在github 上使用我的 selenium 库。

It handles almost the entire jquery API minus the functions that use/require handler passing:

它处理几乎整个 jquery API 减去使用/需要处理程序传递的函数:

HtmlUnitDriver drv = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
drv.setJavascriptEnabled(true);
try {
  jQueryFactory jq = new jQueryFactory();
  jq.setJs(drv);

  drv.get("http://google.com");
  jq.query("[name=q]").val("SeleniumJQuery").parents("form:first").submit();

  String results = jq.queryUntil("#resultStats:contains(results)").text();
  System.out.println(results.split(" ")[1] + " results found!");
} finally {
  drv.close();
}

回答by Jay Stevens

Since you said that you didn't have an ID but a class:

既然你说你没有ID而是一个班级:

(only class-ID provided)

(仅提供类 ID)

...a better answer is likely to use the CSS locator strategy which is already baked-in to Selenium where you can select an element based on a css class or simply by using CSS selector logic (for at least css2 and css3)

...更好的答案可能是使用已经融入 Selenium 的 CSS 定位器策略,您可以在其中选择基于 css 类的元素或简单地使用 CSS 选择器逻辑(至少对于 css2 和 css3)

So to select an element (div, span whatever) that has a specific class you can simply use this for the Selenium locator:

因此,要选择具有特定类的元素(div,span 等),您可以简单地将其用于 Selenium 定位器:

css=.class-ID

You can even use more complicated selectors that are similar to those available in JQuery such as:

您甚至可以使用与 JQuery 中可用的选择器类似的更复杂的选择器,例如:

css=#myDiv .class-ID

This will search for the element with a css style of class-IDwithin the element with an ID = myDiv.

这将class-ID在 ID = 的元素中搜索具有 css 样式的元素myDiv

回答by Lei Cao

  • First you can read the jquery from a jquery.js or jquery.min.js file.
  • Then using execute_script(jquery) to enable jquery dynamically.
  • Now you can interact with jquery.
  • 首先,您可以从 jquery.js 或 jquery.min.js 文件中读取 jquery。
  • 然后使用 execute_script(jquery) 动态启用 jquery。
  • 现在您可以与 jquery 交互了。

here is some code:

这是一些代码:

browser = webdriver.Firefox() # Get local session of firefox

with open('jquery.min.js', 'r') as jquery_js: #read the jquery from a file
    jquery = jquery_js.read()
    browser.execute_script(jquery)  #active the jquery lib

#now you can write some jquery code then execute_script them
js = """
    var str = "div#myPager table a:[href=\"javascript:__doPostBack('myPager','%s')\"]"
    console.log(str)
    var $next_anchor = $(str);
    if ($next_anchor.length) {
        return $next_anchor.get(0).click(); //do click and redirect
    } else {
        return false;
    }""" % str(25) 

success = browser.execute_script(js)
if success == False:
    break

PS: When I use Selenium to fetch some content from some website, they always ban me. Now you should use some proxy to go over it.
here is some code:

PS:当我使用Selenium从某些网站获取某些内容时,他们总是禁止我。现在你应该使用一些代理来检查它。
这是一些代码:

PROXY_HOST = "127.0.0.1"
PROXY_PORT = 8087
SOCKS_PORT = 8088

fp = webdriver.FirefoxProfile()

# Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
fp.set_preference("network.proxy.type", 1)

fp.set_preference("network.proxy.http", PROXY_HOST)
fp.set_preference("network.proxy.http_port", PROXY_PORT)
fp.set_preference("network.proxy.socks", PROXY_HOST)
fp.set_preference("network.proxy.socks_port", SOCKS_PORT)
fp.set_preference("network.proxy.ftp", PROXY_HOST)
fp.set_preference("network.proxy.ftp_port", PROXY_PORT)
fp.set_preference("network.proxy.ssl", PROXY_HOST)
fp.set_preference("network.proxy.ssl_port", PROXY_PORT)

fp.set_preference("network.proxy.no_proxies_on", "") # set this value as desired

browser= webdriver.Firefox(firefox_profile=fp) # with proxy
browser = webdriver.Firefox() # no proxy
browser.get("http://search.example.com") # Load page

elem = browser.find_element_by_id("query_box") # Find the query input
elem.send_keys(u'my query string') # send query string to the input
elem.submit() # submit the query form

回答by Byron Sommardahl

My team just finished a library that wraps jquery functions for use with Selenium. We just finished our first release, but plan on wrapping ALL of jquery's functions. This library makes it easy to use jquery from your Selenium tests in C#. It makes for MUCH cleaner looking tests. Here's the source code: https://github.com/AcklenAvenue/JQSelenium

我的团队刚刚完成了一个包含 jquery 函数以用于 Selenium 的库。我们刚刚完成了我们的第一个版本,但计划包装所有 jquery 的功能。这个库使在 C# 中的 Selenium 测试中使用 jquery 变得容易。它使测试看起来更干净。这是源代码:https: //github.com/AcklenAvenue/JQSelenium

回答by Takaaki Kasai

You could use window.jQuery in getEval command:

你可以在 getEval 命令中使用 window.jQuery:

|getEval | window.jQuery('div#main button').click(); | |

It works for me on Selenium IDE.

它在 Selenium IDE 上对我有用。

For FF3, use wrappedJSObject to get jQuery object:

对于FF3,使用wrappedJSObject来获取jQuery对象:

|getEval | win = (this.page().getCurrentWindow().wrappedJSObject) ? this.page().getCurrentWindow().wrappedJSObject : this.page().getCurrentWindow() | |
|getEval | jq = win.jQuery | |
|assertEval | jq("div#main button").text() | click me! |

回答by ascarb

You'd trigger jquery the same way you'd trigger some java script you'd inject. Try this how-to: http://seleniumhq.org/docs/05_selenium_rc.html#learning-the-api

您可以像触发您要注入的某些 Java 脚本一样触发 jquery。试试这个操作方法:http: //seleniumhq.org/docs/05_selenium_rc.html#learning-the-api