Python中如何使用Selenium定位指定的password类型input输入框元素?
你当前写法的问题是Selenium没有提供find_element_by_type()这个定位方法,可根据元素特征选择以下任意一种稳定的定位方案:
方案1:通过name属性定位(首选,当前元素name属性唯一,稳定性最高)
Selenium 4.0+推荐统一使用By类实现定位,示例代码如下:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By password = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.NAME, "password")) )
方案2:通过CSS选择器匹配密码输入框
如果页面存在多个相同name的元素,可通过type属性精准确认:
password = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'input[type="password"]')) )
方案3:通过XPath定位
password = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Enter your password"]')) )
如果你需要保留lambda的写法,可以调整为如下格式:
password = WebDriverWait(driver,5).until( lambda driver: driver.find_element(By.NAME, "password") )
注意:Selenium 4.0及以上版本已经废弃了
find_element_by_xx系列的旧API,统一使用find_element(By.定位类型, 定位值)的写法可避免版本兼容报错。
内容的提问来源于stack exchange,提问作者HElp
相关产品推荐
相关产品推荐

