1. Install Selenium and WebDriver Manager
Let's start by installing the necessary libraries using pip:
pip install selenium webdriver-manager
Create a Python script (e.g., selenium_wikipedia.py
) and open it in your favorite code editor.
Here is a complete example script that opens Wikipedia, searches for a term, and clicks on the first search result link:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time # Set up the Chrome WebDriver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service) try:
# Open the Wikipedia homepage
driver.get("https://www.wikipedia.org/") # Locate the search input field by its name attribute and enter a search term
search_input = driver.find_element(By.NAME, 'search')
search_input.send_keys('Selenium (software)') # Submit the search form
search_input.send_keys(Keys.RETURN) # Wait for the results page to load and display the results
time.sleep(2) # Click on the first search result link
first_result = driver.find_element(By.CSS_SELECTOR, 'ul.mw-search-results li a')
first_result.click() # Optional: Wait for a few seconds to ensure the page loads completely
time.sleep(5) # Print the title of the current page
print("Page title after click:", driver.title) finally:
# Close the browser
driver.quit()
Run the script using your terminal or command prompt:
python selenium_wikipedia.py
Setting Up WebDriver:
webdriver_manager
library to automatically manage the Chrome WebDriver.webdriver.Chrome(service=service)
.Opening Wikipedia:
driver.get("https://www.wikipedia.org/")
.Searching for a Term:
name
attribute using driver.find_element(By.NAME, 'search')
.'Selenium (software)'
and submits the search form using search_input.send_keys(Keys.RETURN)
.Clicking on the First Search Result:
time.sleep(2)
.driver.find_element(By.CSS_SELECTOR, 'ul.mw-search-results li a')
and clicks on it.Printing the Page Title:
time.sleep(5)
.print("Page title after click:", driver.title)
.Closing the Browser:
driver.quit()
.The script in the example starts the Chrome browser, visits the Wikipedia.org page, searches for "Selenium (software)" in the Wikipedia search box, and clicks on the link returned by the search results.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.