In this Python Selenium article we are going to learn about Browser Interaction in Python Selenium, so Python Selenium is powerful tool for automating web browsers and performing different interactions with web pages. In this tutorial we want to talk about the essential techniques for browser interaction using Python Selenium.
For working with the example of this tutorial you need some requirements, first you should have installed Python in your system, then we need to install Python Selenium and you can use pip for that like this, also you need to driver for specific browser, you can download the driver, and you can add the EXE in your working directory where you Python file is located.
1 |
pip install selenium |
Note: You can download the drivers from here.
To begin interacting with web pages, we need to launch a web browser using Selenium. This is an example of launching Google Chrome:
1 2 3 4 5 6 7 |
from selenium import webdriver # Launch the browser driver = webdriver.Chrome() # Or webdriver.Firefox() for Firefox # Close the browser driver.quit() |
After that the browser is launched, we can navigate to different web pages using the get() method. This is an example of navigating to the GeeksCoders website:
1 2 3 4 5 6 7 8 9 10 |
from selenium import webdriver # Launch the browser driver = webdriver.Chrome() # Or webdriver.Firefox() for Firefox # Navigate to a web page driver.get("https://geekscoders.com") # Close the browser driver.quit() |
Python Selenium provides different methods to interact with web elements, such as clicking buttons, filling out forms and extracting text. This is an example of interacting with a search box on Google:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
from selenium import webdriver from selenium.webdriver.common.by import By # Launch the browser driver = webdriver.Chrome() # Navigate to Google driver.get("https://www.google.com") # Find the search box element search_box = driver.find_element(By.NAME, "q") # Type a search query search_box.send_keys("Python Selenium") # Submit the search query search_box.submit() # Close the browser driver.quit() |
Sometimes, web pages present alerts or popup windows that require interaction. Python Selenium provides methods to handle such alerts. This is an example of accepting an alert:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from selenium import webdriver # Launch the browser driver = webdriver.Chrome() # Or webdriver.Firefox() for Firefox # Navigate to a web page with an alert driver.get("https://www.example.com") # Trigger an alert driver.execute_script("alert('This is an alert!');") # Switch to the alert and accept it alert = driver.switch_to.alert alert.accept() # Close the browser driver.quit() |
Learn More on Python Selenium
- Python Selenium Web Scraping
- Test Automation with Python Selenium
- Python Selenium WebDriver Tutorial
Subscribe and Get Free Video Courses & Articles in your Email