Wait for Visibility
There are certain scenarios in which the element becomes visible after performing certain actions. In such cases, the user can let Selenium webdriver wait until the element is visible. This can be done using ExpectedConditions.visibilityOfElementLocated function. In this approach, we will see how we can wait for the visibility of the element before clicking on it.
Syntax:
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(seconds));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText(element_text)));
Here,
seconds: These are the seconds for which we want the user to wait for the visibility of the element.
element_text: It is the text for which the webdriver needs to wait before clicking on that element.
Example:
In this example, we have opened the Geeks For Geeks website (link) and then waited until the element containing the text ‘Trending Now’ is visible. Once it is visible, we have clicked on that element.
Java
//Importing the Selenium libraries import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import org.openqa.selenium.By; public class selenium3 { public static void main(String[] args) { // Specify the location of the driver System.setProperty( "webdriver.chrome.driver" , "C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe" ); // Initialising the driver WebDriver driver = new ChromeDriver(); // Launch the website // Maximize the screen driver.manage().window().maximize(); // Add explicit wait of 5 seconds WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds( 5 )); // Wait until the element Trending Now is visible wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText( "Trending Now" ))); // Click on the element driver.findElement(By.linkText( "Trending Now" )).click(); } } |
Output:
How to Force Selenium WebDriver to Click on Element which is Not Currently Visible?
A programming language that is used to execute a set of instructions that a computer can understand and execute to perform various tasks is known as Java. Java can be controlled autonomously using various automation tools.
Table of Content
- Visibility criteria
- Wait for Visibility
- Scroll the Element into View
- Address Underlying Issues
- Forceful Click using JavaScript
- Conclusion
- FAQs
Selenium is one such tool, that can make the work of developer and tester easier. There are various instances when the user needs to click or perform a certain action on the element that is currently not in the scope of visibility. In this article, we will see how we can forcefully click on an element that is not currently visible using Selenium webdriver.