Selenium is an open-source automation testing tool that is widely used in the software testing industry. It helps developers and testers to automate browser-based testing to ensure the smooth functioning of web applications. Selenium is an easy-to-use tool that supports a variety of programming languages, including Java, Python, C#, and more. In this article, we’ll discuss the most commonly used and essential Selenium commands that every beginner should know.
The first step to using Selenium is launching a browser. The following command is used to launch a browser in Selenium:
driver = webdriver.Firefox()
This command launches the Firefox browser. Similarly, we can use other browser drivers such as Chrome, Safari, and Internet Explorer.
Navigating to a URL
Once the browser is launched, the next step is to navigate to a URL. The following command is used to navigate to a URL:
This command will navigate to the URL specified in the argument.
Selenium provides several ways to find elements on a web page, such as by ID, name, class, and more. The following commands are used to find elements:
element = driver.find_element_by_id("id_name") element = driver.find_element_by_name("name_value") element = driver.find_element_by_class_name("class_name")
Interacting with Elements
After finding an element, we can interact with it. For example, we can click a button, enter text into a textbox, and more. The following commands are used to interact with elements:
Waiting for Elements
Sometimes, elements take some time to load on a web page. In such cases, we need to wait for the element to load before interacting with it. The following commands are used to wait for an element:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "id_name")))
This command waits for 10 seconds for the element to be present on the web page.
Switching to Frames
Sometimes, web pages contain frames within frames. To interact with elements inside a frame, we need to switch to that frame. The following command is used to switch to a frame:
This command switches the control to the frame specified in the argument.
We can maximize the browser window using the following command:
This command maximizes the browser window to its full-screen size.
Getting Text from Elements
We can get the text from elements using the following command:
element_text = element.text
This command gets the text from the element and stores it in the element_text variable.
Finally, we can close the browser using the following command:
This command closes the current browser window.