记录一个实现搜索功能的爬虫
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
# 创建WebDriver
driver = webdriver.Firefox() # 打开网页
driver.get("https://www.jd.com/?cu=true") # 替换为你要搜索的网站地址 # 定位搜索框并输入关键词
search_box_xpath = '//*[@id="key"]' # 替换为实际的搜索框XPath
search_box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, search_box_xpath)))
search_box.send_keys("替换为要搜索的关键词") # 替换为要搜索的关键词 # 触发搜索
# 方法一:按下回车键触发搜索
search_box.send_keys(Keys.RETURN)# 方法二:点击搜索按钮触发搜索(如果有搜索按钮的话)
# search_button_xpath = "/html/body/div[1]/div[4]/div/div[2]/div/div[2]/button" # 替换为实际的搜索按钮XPath
# search_button = driver.find_element(By.XPATH, search_button_xpath)
# search_button.click() # 关闭浏览器(在完成所有操作后)
# driver.quit()