Step 1: Install Selenium
Open a terminal or command prompt and run the following command to install the Selenium library via pip:
pip3 install selenium
Step 2: Download and Install WebDriver
Similar to the way described in previous responses, you need to download and install the WebDriver corresponding to the browser you want to use.
Step 3: Write Python Code
Below is an example of how to use Selenium to open a web page, perform a search, and retrieve content:
from selenium import webdriver # Initialize the browser (using Chrome in this example) driver = webdriver.Chrome() # Open a web page driver.get("https://www.example.com") # Find an element on the web page search_box = driver.find_element_by_name("q") search_box.send_keys("Hello, Selenium!") search_box.submit() # Print the web page content after the search print(driver.page_source) # Close the browser driver.quit()
Note that the example above uses the Chrome browser. If you want to use a different browser, you need to replace
webdriver.Edge() according to the browser you want to use.
- Selenium requires a WebDriver to control the web browser. Make sure you have installed and set up the correct path to the WebDriver.
- When using Selenium to automate web browser interactions, be mindful of interacting with security measures on the website and adhere to the website's policies.