首页 > 解决方案 > 使用 Selenium 选择时按钮失去作用

问题描述

我正在尝试使用 Python 使用 Selenium 自动化登录流程。当我手动完成流程时,一切都按预期工作。我可以使用 webdriver 加载网页,但是一旦我选择了用户名字段,我在尝试提交时会在浏览器控制台中看到以下错误:

ERROR TypeError: Cannot read property 'action' of null

我尝试通过 Selenium 导航到该页面,然后手动填写用户名,它将成功提交。但是,如果我的脚本导航到该页面然后选择目标字段,则即使我在脚本等待时手动填写并提交该字段,也会在提交该字段时出现错误。我知道该字段已成功定位,因为 send_keys 调用正确填写了它。通过 Selenium 选择页面上的任何元素都会导致同样的问题。似乎这只影响触发页面更新而没有路由的控件;链接到其他页面的按钮仍按预期工作。

我的代码在这个阶段非常基础,大致如下所示:

chrome_options = Options()
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=chrome_options)

driver.get("https://www.targetwebsite.com")

# Executing this line, or anything using a locator, seems to cause the issue
element = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.ID, "usernameTextBox")))

element.send_keys("username")
element.send_keys(Keys.ENTER)

我要定位的输入字段:

<input _ngcontent-c7 appformatter class="text_box input_box ng-pristine ng-invalid remote-accessable focusable ng-touched" id="usernameTextBox" type="text" aria-label="username">

我尝试换掉 Chromedriver 并将 Geckodriver 与 Firefox 一起使用,但遇到了同样的问题。知道是什么原因造成的吗?在使用 Selenium 之前,我从未见过这样的事情。

标签: pythonseleniumselenium-webdriver

解决方案


尝试使用 JavaScript 与元素交互,看看是否有相同的行为。做这样的事情:

script = "arguments[0].value=" + username         #if element is input type
script = "arguments[0].innerText=" + username     #if element is button
driver.execute_script(script,element)

对于 Enter 键,检查是否可以通过单击按钮来完成。否则使用与使用硒相同的方法。


推荐阅读