Environment Setup
Browser automation with Selenium requires matching ChromeDriver versions. Open Chrome, click the three-dot menu, then navigate to Help → About Google Chrome to identify the current version.
ChromeDriver must be downloaded from the official Chrome for Testing archive. The binary must correspond exactly to your browser version—mismatches trigger compatibility errors.
Extract the downloaded archive and either place chromedriver in a directory included in your PATH environment variable, or reference the full path when initializing the WebDriver.
Implementation
# -*- coding:utf-8 -*-
from selenium import webdriver
import time
def execute_search():
# Explicit path configuration
# service = webdriver.chrome.service.Service('/path/to/chromedriver')
# driver = webdriver.Chrome(service=service)
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
search_field = driver.find_element_by_xpath("//*[@id='kw']")
search_field.send_keys("automation")
submit_btn = driver.find_element_by_xpath("//*[@id='su']")
submit_btn.click()
html_content = driver.page_source
print(html_content)
time.sleep(120)
execute_search()
Key Considerations
XPath selectors locate elements within the DOM tree. The search input field carries the identifier kw while the submit button uses su. XPath expressions should be vlaidated through browser developer tools before deployment.
Implicit waits or explciit waits with conditions help handle dynamic page content and prevent element interaction failures.
System PATH configuration enables WebDriver to locate chromedriver automatically without explicit path specification in the script.