Selenium is very useful for automated testing of web systems, It takes a long time to write test code manually Wait for it to be clickable, click with action, etc. I can't operate it as if I didn't get the hang of it, and it's quite difficult to get to it at first.
For example, a code that just clicks on an element would look like this:
WebElement element = driver.findElement(By.id("id"));
wait.until(ExpectedConditions.elementToBeClickable(element));
Actions actions = new Actions(driver);
actions.click(element);
I tried to write this like JQuery as follows.
$("#id").click();
Since I also implemented find and children, I can write the code to get the number of rows in a table as follows.
$("#id").find("TBODY").children("TR").size();
If this is the case, anyone who can use JQuery can write it without knowing selenium.
To use it, just drop the following source on github and prepare the following method on the test class side. (Keep the driver as a class variable)
https://github.com/widora99/seleniumTest/blob/master/ExtendElement.java
public static ExtendElement $(String selector) {
return new ExtendElement(driver, driver.findElement(By.cssSelector(selector)));
}
If you want to get multiple elements, please also create the following method. (Due to Java restrictions, it is necessary to specify the return type, so there is no choice but to use another method.)
public static List<ExtendElement> $$(String selector) {
ExtendElement ele = new ExtendElement(driver, driver.findElement(By.tagName("body")));
return ele.finds(selector);
}
ExtendElement is a class that extends WebElement, Instead of implementing WebElements to make it look like JQuery The method is defined with its own name. For example, getText () becomes text (). doubleClick () is dblclick ().
Children had the hardest time. In Selenium's cssSelector, specifying "> *" will result in an error, so I have no choice but to convert it to xPath and get it.
public List<ExtendElement> children(String selector) {
List<ExtendElement> elist = new ArrayList<ExtendElement>();
String xpath = cssToXpath(selector);
List<WebElement> wlist = elm.findElements(By.xpath("./" + xpath));
for(WebElement welm : wlist) {
elist.add(new ExtendElement(driver, welm));
}
return elist;
}
However, since the class name is compared by String, "img2" will hit by specifying "img", There is a problem that multiple class names cannot be specified. (Same for closest)
I couldn't do it with my own knowledge, so If anyone knows a good way, I would appreciate it if you could comment or pull.
Recommended Posts