无法使用Selenium,Python和chromedriver与页面中的元素进行交互

时间:2019-04-22 22:41:42

标签: python selenium

我正在尝试使用Selenium,chr​​omedriver和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 :(得分:0)

与其使用睡眠命令,不如使用等待条件。您可以等待某种条件出现,然后再继续。这应该有助于避免元素不可见,不可点击等问题。

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

答案 1 :(得分: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++;
}

` 添加这些额外的几行代码将使单击更加可靠,脚本将尝试单击循环中的元素。