提问人:Amin Affandi 提问时间:10/27/2023 更新时间:10/27/2023 访问量:64
Python Selenium:使用选择器时无法找到元素 [NoSuchElementException CLASS_NAME
Python Selenium Unable to locate element [NoSuchElementException] when using CLASS_NAME selector
问:
当我尝试使用时,它将始终返回 NoSuchElementException,无法找到元素。
但是当我在同一元素上使用 ID 和 NAME 时,它起作用了!只有CLASS_NAME失败了。find_element(By.CLASS_NAME, 'classname')
这是 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)
Username1 失败,username2 通过。
我尝试更改为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']"))
但这些都不起作用。
答:
1赞
Yuri R
10/27/2023
#1
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")
评论