??定位網頁元素后,Selenium模塊支持點擊、發送文本或按鍵、清除內容等操作。本文以百度網站為例學習并測試這幾類操作的基本用法。
首先是發送文本或按鍵,主要用到send_keys函數,如果是發送文本,則直接將文本內容作為函數入參即可,如果是發送按鍵,則可使用selenium.webdriver.common.keys定義的按鍵作為函數入參(按鍵類詳細說明見參考文獻6)。下面的示例找到百度網站的輸入框,輸入“網易郵箱地址”,然后模擬按回車鍵,代碼及運行效果如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import timedriver = webdriver.Chrome()
driver.get("https://www.baidu.com")time.sleep(2)search_box = driver.find_element(By.ID, "chat-textarea")
search_box.send_keys("網易郵箱地址")
search_box.send_keys(Keys.RETURN)time.sleep(3)first_result = driver.find_element(By.CSS_SELECTOR, "div.result:first-child h3 a")
first_result.click()
??點擊操作主要調用click函數,調整上面的示例,輸入搜素內容后,找到并點擊搜索按鈕,示例代碼如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import timedriver = webdriver.Chrome()
driver.get("https://www.baidu.com")time.sleep(2)search_box = driver.find_element(By.ID, "chat-textarea")
search_box.send_keys("網易郵箱地址")search_btn = driver.find_element(By.ID, "chat-submit-button")
search_btn.click()time.sleep(3)first_result = driver.find_element(By.CSS_SELECTOR, "div.result:first-child h3 a")
first_result.click()
??清除內容操作主要調用clear函數,調整上面的示例,先輸入搜素內容“網易郵箱地址”,點擊搜索按鈕,再找到新頁面的輸入框輸入“qq郵箱地址”,再點擊搜索按鈕,最后點擊第一個檢索結果。示例代碼如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import timedriver = webdriver.Chrome()
driver.get("https://www.baidu.com")time.sleep(2)search_box = driver.find_element(By.ID, "chat-textarea")
search_box.send_keys("網易郵箱地址")search_btn = driver.find_element(By.ID, "chat-submit-button")
search_btn.click()time.sleep(3)search_box = driver.find_element(By.ID, "chat-textarea")
search_box.clear()
search_box.send_keys("qq郵箱地址")
time.sleep(3)search_btn = driver.find_element(By.ID, "chat-submit-button")
search_btn.click()time.sleep(3)first_result = driver.find_element(By.CSS_SELECTOR, "div.result:first-child h3 a")
first_result.click()
)
參考文獻:
[1]https://www.selenium.dev/zh-cn/
[2]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/
[3]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502
[4]https://registry.npmmirror.com/binary.html?path=chromedriver/
[5]https://chromedriver.chromium.org/
[6]https://juejin.cn/post/7028451097559695397?from=search-suggest