鼠标操作
鼠标操作:Action.Chains 分为 操作+执行
操作包括但不限于如下几种:
- 悬浮:move_to_element
- 单击:click
- 双击:double_click
- 点击并按住:click_and_hold 释放 relese
- 拖拽:drag_and_drop
- 执行:perform()
from time import sleepfrom selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWaitdriver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
loc = (By.ID, 's-usersetting-top')
# 先找到鼠标需要操作的元素对象
ele = driver.find_element(*loc)
# 实例化ActionChains
ac = ActionChains(driver)
# 调用鼠标操作
# ac.move_to_element(ele)
# 调用后返回对象,继续点击操作并执行
ac.move_to_element(ele).click(ele)
# 调用perform()执行鼠标操作,执行后会清空相关信息
ac.perform()
# 等待下拉列表元素可见
loc = (By.XPATH, '//a[text()="高级搜索"]')
wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located(loc))
driver.find_element(*loc).click()
sleep(2)
# 点击元素,出现下拉列表
loc = (By.XPATH, "//span[text()='所有网页和文件']")
wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located(loc))
driver.find_element(*loc).click()
sleep(1)# 等待下拉列表中要操作的元素可见,然后执行操作
loc = (By.XPATH, '//p[@data-value="doc"]')
wait = WebDriverWait(driver, 20)
wait.until(EC.visibility_of_element_located(loc))
driver.find_element(*loc).click()
sleep(1)
driver.quit()
select 类
select_by_value
select_by_index
select_by_visible_text
1、找到页面有Select的信息
2、找到Select元素
3、实例化Select类,将select元素对象传进去
4、通过[下标/value/文本]选值
from selenium.webdriver.support.select import Select
from selenium import webdriver
from time import sleep
driver=webdriver.Chrome()
driver.get(r"有select元素的页面")
# 找到select元素
ele=driver.find_element("id","hobby")
# 实例化select类,将select元素对象传进去
s=Select(ele)
# 通过[下标/value/文本]选值
s.select_by_value("看电影")
sleep(2)
s.select_by_index(2)
sleep(2)
s.select_by_visible_text("唱歌")
sleep(3)
driver.quit()