首页 > 解决方案 > 如何修复硒,元素不可交互?

问题描述

所以我正在尝试创建一个程序来解决用户输入的复杂数学问题。我正在使用网站 mathpapa 来解决这些方程。

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

PATH = 'C:\Program Files\chromedriver.exe'

message = input("Enter a math problem: ")

web = webdriver.Chrome(PATH)
web.get('https://www.mathpapa.com/algebra-calculator.html')


equation = web.find_element_by_xpath('//*[@id="source3"]/span[2]')
equation.send_keys(message + Keys.RETURN)

answer = WebDriverWait(web, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="solout3"]/div[2]')))
print(answer.text)

我在线上遇到错误equation = web.find_element_by_xpath('//*[@id="source3"]/span[2]') 错误是说元素不可交互,有没有其他方法可以将消息输入到 mathpapa 上的文本栏中?

标签: pythonseleniumselenium-webdriver

解决方案


您的代码有两个问题:

  1. 您正试图在页面完全加载之前访问方程式输入元素。
    这就是您收到该错误的原因。
    您必须在此之前添加一个等待。
    我还更改了定位器以更精确。
equation = WebDriverWait(web, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#source3 textarea')))
equation.send_keys(message + Keys.RETURN)
  1. 此外,您为答案元素使用了错误的定位器。
    尝试这个:
answer = WebDriverWait(web, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div#solout3 mn')))
print(answer.text)

推荐阅读