学习Python中Selenium模块的基本用法(7:元素操作-1)

发布于:2025-08-29 ⋅ 阅读:(16) ⋅ 点赞:(0)

  定位网页元素后,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 time

driver = 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 time

driver = 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 time

driver = 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


网站公告

今日签到

点亮在社区的每一天
去签到