selenium定位下拉框:selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable: Element is not currently
有时候元素定位出错,显性等待可以很好解决
- presence_of_element_located: 当我们不关心元素是否可见,只关心元素是否存在在页面中。
- visibility_of_element_located: 当我们需要找到元素,并且该元素也可见。
场景:访问百度,找到右上角设置,点击下拉中的搜索设置。每页条数初始是10,修改每页条数为20
1 from selenium import webdriver
2 import time
3 from selenium.webdriver.support.select import Select
4 from selenium.webdriver.common.keys import Keys
5 from selenium.webdriver.common.action_chains import ActionChains
6 from selenium.webdriver.support.wait import WebDriverWait
7 from selenium.webdriver.support import expected_conditions as ec
8 from selenium.webdriver.common.by import By
9 driver = webdriver.Chrome()
10 driver.maximize_window()
11 driver.get("http://www.baidu.com")
12 driver.implicitly_wait(10)
13 driver.find_element_by_id("kw").send_keys("selenium")
14 driver.find_element_by_id("su").send_keys(Keys.ENTER)
15 # 鼠标悬停
16 mouse = driver.find_element_by_name("tj_settingicon")
17 ActionChains(driver).move_to_element(mouse).perform()
18 driver.find_element_by_link_text("搜索设置").click()
19 # 隐式等待
20 driver.implicitly_wait(5)
21 # 定位下拉框
22 select = driver.find_element_by_name("NR")
23 # 显式等待,待元素可见
24 # WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.NAME, "NR")))
25 Select(select).select_by_visible_text("每页显示20条")
26 print("下拉框选择的最新条数是:", select.get_attribute('value'))
27 #等待2秒,为了看到效果
28 time.sleep(2)
29 driver.quit()
没加第24行代码前,一直报错selenium.common.exceptions.ElementNotInteractableException
加行代码完美解决:
# 显式等待,待元素可见
WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.NAME, "NR")
“学习必须如蜜蜂一样,采过许多花,这才能酿出蜜来。”