DEV Community

digitalized-snake
digitalized-snake

Posted on

Getting Started with Selenium (Python)

Introduction

Selenium is a powerful tool for automating web browsers, and it can be especially useful for web developers looking to test their applications or automate repetitive tasks. Here are some useful commands for working with Selenium in Python.

Installing Selenium

Before we can use Selenium, we need to install it. We can install Selenium using pip, the Python package manager. Simply open a terminal or command prompt and type:

pip install selenium

Starting a Browser Session

To begin working with Selenium, we need to start a browser session. We can do this with the webdriver module. Here's an example of starting a session with Chrome:

from selenium import webdriver

driver = webdriver.Chrome()
Enter fullscreen mode Exit fullscreen mode

This will start a new Chrome window, and the driver object will be our interface for interacting with the browser.

Navigating to a URL

Once we have a browser session, we can navigate to a URL using the get method. Here's an example:

driver.get("https://www.example.com")
Enter fullscreen mode Exit fullscreen mode

This will load the specified URL in the browser window.

Finding Elements

One of the most powerful features of Selenium is its ability to find elements on a web page. We can do this using the find_element method. Here are a few examples:

# Find an element by ID
find_element(By.ID, "id")

# Find an element by name attribute
find_element(By.NAME, "name")

# Find an element by xpath
find_element(By.XPATH, "xpath")

# Find a hyperlink
find_element(By.LINK_TEXT, "link text")
find_element(By.PARTIAL_LINK_TEXT, "partial link text")

# Find an element by its tag name
find_element(By.TAG_NAME, "tag name")

# Find an element through its class name
find_element(By.CLASS_NAME, "class name")

# Find an element with its CSS selector
find_element(By.CSS_SELECTOR, "css selector")
Enter fullscreen mode Exit fullscreen mode

Once we have a reference to an element, we can interact with it in various ways. For example, we can get its text content with the text attribute:

# get the text content of an element
text = element.text
Enter fullscreen mode Exit fullscreen mode

Additional Information

Since this is just a basic introduction, a lot of aspects of Selenium have been left out. For the full documentation, head to their official doc site.

Top comments (0)