Python Selenium 使用 CLASS_NAME 选择器时无法定位元素 [NoSuchElementException]

问题描述 投票:0回答:1

当我尝试使用

find_element(By.CLASS_NAME, 'classname')
时,它总是会返回NoSuchElementException,无法定位元素。 但是当我在同一个元素上使用 ID 和 NAME 时,它起作用了!只有 CLASS_NAME 失败。

这是 HTML

<input type="text" name="login" id="login_field" class="form-control input-block js-login-field" autocapitalize="off" autocorrect="off" autocomplete="username" autofocus="autofocus">

这是脚本

username1 = driver.find_element(By.CLASS_NAME,"form-control input-block js-login-field")
username2 = driver.find_element(By.ID,"login_field")
print(username1)
print(username2)

用户名1失败,用户名2通过。

我尝试更改为 cssSelector:

username1 = driver.findElement(By.cssSelector("input.form-control input-block js-login-field"));

我也尝试过更改语法:

username1 = driver.find_element(By.CLASS_NAME("input[class='form-control input-block js-login-field']"))

但是都不起作用。

python selenium-webdriver css-selectors classname nosuchelementexception
1个回答
0
投票

Selenium 中的

By.CLASS_NAME
方法设计用于处理单个类名,而不是多个类名。

该元素有多个类:

form-control
input-block
js-login-field
。您应该选择这些类之一来与
By.CLASS_NAME
一起使用。

username1 = driver.find_element(By.CLASS_NAME, "form-control")

使用

By.CSS_SELECTOR
作为复合类名称

username1 = driver.find_element(By.CSS_SELECTOR, ".form-control.input-block.js-login-field")
© www.soinside.com 2019 - 2024. All rights reserved.