使用Selenium、Python和Chromedriver无法与页面元素交互

3
我正在尝试使用selenium,chromedriver和python登录页面(https://www.aprovaconcursos.com.br/questoes-de-concurso/cliente/login)。虽然元素很容易找到,但我无法弄清楚如何与它进行交互。
我正在使用Python 3.7,Chromedriver和Windows 10运行它。不认为这可能是问题所在。似乎有一些元素覆盖了我要输入数据的输入框,但我无法弄清楚是什么。
下面是我用来做这件事的代码。
**def login(username, senha):

    #entra no site e faz login

    driver.get('https://www.aprovaconcursos.com.br/questoes-de-concurso/cliente/login')
    time.sleep(30)
    site_username = driver.find_element_by_id("username")
    site_username.clear()
    site_username.send_keys(username)
    site_password = driver.find_element_by_id("password")
    site_password.clear()
    site_password.send_keys(senha)
    driver.find_element_by_class_name("btn btn-primary").click()**

问题如下:
Traceback (most recent call last):
   File "***.py", line 161, in <module>
        login(username,senha)
   File "***.py", line 125, in login
        site_username.clear()
   File "C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 95, in clear
        self._execute(Command.CLEAR_ELEMENT)
   File "C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
        return self._parent.execute(command, params)
   File "C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
        self.error_handler.check_response(response)
   File "C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
        raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable   (Session info: chrome=73.0.3683.103)   (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT
    10.0.17134 x86_64)

编辑

问题似乎与EC无关。尝试了提供的解决方案,但条件从未出现。

2个回答

0

与其使用sleep命令,更加推荐使用等待条件。您可以等待某个条件出现后再继续执行。这应该有助于避免元素不可见、不可点击等问题。

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.ID, 'username')))

你可以在以下链接中找到更多有关等待的帮助:

https://selenium-python.readthedocs.io/waits.html

https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html


谢谢你的帮助。我尝试了一下,代码按预期工作:webdriver等待。但问题是它会一直等待下去。我认为输入框上方有些东西我没有看到,这就是问题的原因。 - great_coder

0

你应该添加 while 循环,例如:

`

int x = 0;
while (x < 3) {
try {
WebElement we = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
we.click();
break;
} catch (WebDriverException e) {
}
x++;
}

添加这几行额外的代码将使点击更加稳健,脚本会尝试在循环中点击元素。


问题出在 EC 上:它从未到来。我认为我在构建这些输入框的方式上漏掉了一些东西。 - great_coder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接