← Back to Libraries🌐 Web Development
📦

Selenium in Python

Learn how to automate web tasks using Selenium with Python in this comprehensive guide.

pip install selenium

Overview

Paragraph 1: Selenium is a powerful tool for controlling web browsers through programs and automating browser tasks. It's widely used for testing web applications and web scraping, providing a programmable interface to interact with web content.

Paragraph 2: Key features of Selenium include support for multiple browsers like Chrome, Firefox, and Safari, and the ability to simulate real user interactions with web elements. Common use cases include automated testing, web scraping, and browser automation for repetitive tasks.

Paragraph 3: To get started with Selenium in Python, you need to install the Selenium package and a web driver for your preferred browser. Common patterns include initializing the driver, opening a web page, interacting with web elements, and closing the browser session.

Code Examples

Open a webpage

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.example.com')
browser.quit()

Find element by ID

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.example.com')
element = browser.find_element_by_id('element-id')
browser.quit()

Fill a form and submit

from selenium import webdriver
from selenium.webdriver.common.by import By

browser = webdriver.Chrome()
browser.get('https://www.example.com/form')
input_element = browser.find_element(By.NAME, 'username')
input_element.send_keys('my_username')
submit_button = browser.find_element(By.ID, 'submit')
submit_button.click()
browser.quit()

Take a screenshot

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.example.com')
browser.save_screenshot('screenshot.png')
browser.quit()

Handle alerts

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.example.com/alert')
alert = browser.switch_to.alert
alert.accept()
browser.quit()

Common Methods

get

Loads a web page in the current browser session.

find_element_by_id

Finds an element by its ID attribute.

find_element_by_name

Finds an element by its name attribute.

find_element_by_xpath

Finds an element using an XPath expression.

click

Clicks on an element.

send_keys

Sends keystrokes to an element.

save_screenshot

Saves a screenshot of the current window.

switch_to.alert

Switches to the currently active alert dialog.

accept

Accepts the alert dialog.

quit

Closes the browser session.

More Web Development Libraries