We have discussed Selenium WebDriver previously. Now let’s see how can we use its functionality in Java API for querying elements on a web page and iteracting them.
There are two methods in Selenium WebDriver API that provides selection of DOM element:
- driver.findElement([selector]) – returns a WebElement object found by selector passed as argument
- driver.findElements([selector]) – returs a list of elements
Selenium selectors in Java
Now let’s learn more about selectors. As we said before, we need to pass a selector to findElement() method argument. In selenium we use the By class with static methods for picking elements. Here is an example of selecting element by its id:
WevElement header = driver.findElement(By.id("header_id"));
There are 8 types of By selection mothods:
- By.xpath(String xpath) – uses XPath expression to find elements
- By.id(String id) – uses element’s id attribute
- By.className(String className) – uses HTML class attribute
- By.cssSelector(String cssSelector) – finds by CSS expression
- By.linkText(String linkText) – finds links with specified text
- By.partitialLinkText(String linkText) – finds links elements that contain specified text
- By.name(String name) – finds elements by name attribute
- By.tagName(String tagName) – finds elements by the HTML tag name
Selenium select link by text
Let’s implement a common example – query a link by it’s text for clinking on it.
WebDriver driver = new FirefoxDriver(); driver.get("http://10minbasics.com"); WebElement homeLink = driver.findElement(By.partialLinkText("10 Min Basics")); homeLink.click(); Thread.sleep(5000); // hardcoded to check that link was clicked driver.close();
This code will open a new Firefox browser window using Selenium’s WebDriver after calling the get() method.
Then we select the link WebElement by By.partialLinkText() selector. WebDriver will try to find this element on the page. If there’s no element found it will return null.
Now we can interact with this link. In the code we call the method click() on it to simulate a real left mouse button clink.
Thread.sleep(5000) is a bad practice but we use it to force system to wait 5 seconds. We need it to check that the link was really clicked.
That’s all. In the next chapter we will cover the Page Object pattern for test automation.
Leave a Reply
1 Comment on "Query elements with Selenium and Java"
ddd