首页 > 解决方案 > 元素不可交互的 Selenium Python

问题描述

我正在尝试将密钥发送到https://www.wolframalpha.com/上的文本框,但如您所见,我遇到了一个错误。我已经尝试过查看这些元素,但如果您能够提供帮助,我将不胜感激。使用python3.7,我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time 
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions() 
options.add_experimental_option("excludeSwitches", ["enable-logging"])
driver = webdriver.Chrome(options=options, executable_path=r'C:\Program Files (x86)\Chrome\Application\chromedriver.exe')

driver.get('https://www.wolframalpha.com/')

driver.find_element_by_xpath('_9CcbX').send_keys('1+1')

错误

traceback (most recent call last):
  File "c:/Users/gabri/Desktop/BOT/IXL Bot - Gabriel.py", line 15, in <module>
    driver.find_element_by_xpath('_9CcbX').send_keys('1+1')
  File "C:\Users\gabri\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\gabri\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\gabri\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\gabri\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"_9CcbX"}        
  (Session info: chrome=88.0.4324.146)

标签: pythonselenium-webdriver

解决方案


首先,您会得到NoSuchElementException,因为您正在通过 xpath 搜索,并带有类名参数。(_9CcbX是一个类名)。相反,您可以复制元素的正确 xpath:

  • 检查
  • 右键单击元素
  • 复制 -> 复制完整的 xpath

这会给你:

driver.find_element_by_xpath('/html/body/div/div/div/div/div/div[1]/section/form/div/div/input').send_keys('1+1')

其次,您应该使用WebdriverWait以确保元素已加载并且可交互。

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

xpath = '/html/body/div/div/div/div/div/div[1]/section/form/div/div/input'
element = wait.until(EC.element_to_be_clickable(driver.find_element(By.XPATH, xpath)))
element.send_keys('1+1')

推荐阅读