如何使用Selenium和Python查找并单击元素以登录

2024-10-03 06:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法找到并单击元素。HTML如下:

<button _ngcontent-c2=""> INICIAR SESIÓN </button>

我试着用代码:

^{pr2}$

这是我得到的错误:

Traceback (most recent call last):
  File "/home/eitan/PycharmProjects/pysel/autopro.py", line 36, in <module>
    login_element = driver.find_element_by_xpath('/html/body/app-root/div/div/app-login/form/div/div/button').click()
  File "/home/eitan/PycharmProjects/pysel/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/home/eitan/PycharmProjects/pysel/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "/home/eitan/PycharmProjects/pysel/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/eitan/PycharmProjects/pysel/venv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <button _ngcontent-c2="">...</button> is not clickable at point (624, 648). Other element would receive the click: <img _ngcontent-c2="" src="assets/static/images/login.svg">
  (Session info: chrome=74.0.3729.131)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Linux 4.15.0-47-generic x86_64)

Tags: inpydivhomevenvseleniumlinebutton
2条回答

由于元素是Angular元素,要在文本为INICIAR SESIÓN的元素上click(),您需要为element_to_be_clickable()归纳WebDriverWait,并且可以使用以下Locator Strategy

  • 使用XPATH

    driver.execute_script("arguments[0].click();",WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'INICIAR SESIÓN')]"))))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

尝试下列操作xpath

login_element = driver.find_element_by_xpath("//button[contains(.,'INICIAR')]"
login_element.click()

已编辑

似乎webdriver无法单击按钮元素.注入java脚本执行器单击按钮元素或使用action类单击。在

^{pr2}$

或者动作类。在

login_element = driver.find_element_by_xpath("//button[contains(.,'INICIAR SESIÓN')]")
ActionChains(driver).move_to_element(login_element).click().perform()

对action类使用以下导入。在

from selenium.webdriver.common.action_chains import ActionChains

相关问题 更多 >