Selenium – 将“WebElement”转换为Javascript或JQuery对象的通用方法

我有一个简单的WebElement,我想在我的对象上执行一系列(一个或多个)JS / JQuery类型的操作。

大多数情况下这很简单,我只需获取对象的ID,将其传递到“ExecuteScript”函数中,并且中提琴效果很好:

RemoteWebDriver driver = ...; var element = driver.FindElementByXPath("..."); //Or any other type of lookup driver.ExecuteScript(@"$('#" + element.GetAttribute("id") + "')."DoSomeStuff...;"); 

20%这根本不起作用,因为该项目没有ID。 当然,有许多方法可以在Selenium中查找项目以及在jQuery或Javascript中查找项目的许多方法,但它们并不总是映射,虽然可以在jQuery中构造一个可以查找Selenium对象的查询,方法对于每种对象类型都不一样。

搜索它似乎大多数人使用“id”方法(例如: 1,2,3 )。 你可以用相反的方式做到这一点 。 另一个想法是在jQuery中访问它之前给每个元素在selenium中提供一个唯一的ID,但它看起来不会起作用,因为设置它需要使用Javascript或jQuery。

我还没有找到一种方法来为每个元素做这个普遍的事情,如何做到这一点?

您可以并且始终能够通过ExecuteScript在JavaScript中来回传递元素引用。 是否可以将这些原始DOM元素转换为JQuery使用,这是我没有资格发言的问题。 然而,在JavaScript代码中引用WebDriver-found元素的代码将是这样的:

 // Assume element holds a reference to an already-found // IWebElement, found using the standard WebDriver FindElement // methods, and that driver is a properly-instantiated // IWebDriver object. // NB, doing proper casting here, since it's idiomatic in // the WebDriver library to code to the interface, not the concrete // implementation. IJavaScriptExecutor executor = driver as IJavaScriptExecutor; executor.ExecuteScript("alert(arguments[0].tagName);", element); 

上面的代码将抛出一个警告(并阻止你的Selenium代码),显示元素的tagName JavaScript属性。 您可以使用此技术来使用该元素,就像在页面中使用JavaScript一样。