快速开始
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://selenium.dev")
driver.quit()
小例子
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import time
chrome_driver_path = "/Users/cai/Documents/chromedriver-mac-x64/chromedriver" # 替换为你本地的路径
service = Service(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=service)
driver.get("https://www.xiaocaicai.com")
time.sleep(2) # 等待页面加载
# 定位搜索框并输入
print("定位搜索框")
search_box = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, 'input[id="search-field"]'))
)
search_query = 'python'
print(f"输入搜索内容: {search_query}")
search_box.send_keys(search_query)
search_box.send_keys(Keys.RETURN)
# 等待搜索结果加载
print("等待搜索结果加载")
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, 'div[id="loop-container"]'))
)
time.sleep(2) # 确保内容完全加载
container = driver.find_element(By.CSS_SELECTOR, 'div[id="loop-container"]')
articles = container.find_elements(By.TAG_NAME, 'article')
for article in articles:
titles = article.find_elements(By.XPATH, ".//h2[@class='post-title']")
a_tags = titles[0].find_elements(By.TAG_NAME, "a")
print(a_tags[0].text, a_tags[0].get_attribute('href'))
articles[0].find_elements(By.XPATH, ".//h2[@class='post-title']")[0].find_elements(By.TAG_NAME, "a")[0].click()
time.sleep(30)
driver.quit()