使用Selenium的困难:无法定位元素

问题描述 投票:0回答:1

我很困惑,因为在使用 Selenium 时,我收到错误消息“无法找到元素”。通常,我用来获取 XPATH 或 CSS_SELECTOR 信息的技术是在 Web 浏览器中使用检查,然后复制到我的 python 代码中。它在过去有效,所以我不确定在这种情况下我做错了什么。

在 driver.find_element 上失败。它还在 Webdriverwait 代码行上失败。 第一个 driver.find_element 用于查找清除按钮。 webdriverwait 尝试查找股票输入框(默认为 AAPL)。

代码是:


import os
import time
import numpy as np
import pandas as pd
from datetime import date
from datetime import datetime as dt
import matplotlib.pyplot as plt
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
options = Options()
options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe"
driver = webdriver.Firefox(options=options)
driver.maximize_window()
driver.get('https://huggingface.co/spaces/FinGPT/FinGPT-Forecaster')

time.sleep(10)


search2=driver.find_element(By.XPATH,'//*[@id="component-14"]')
search2.click()


search=WebDriverWait(driver, 10).until(EC.presence_of_element_located(
    (By.CSS_SELECTOR, '#component-0 > label:nth-child(1) > textarea:nth-child(3)'))).click()



search.send_keys('IBM')



错误信息是: 回溯(最近一次调用最后一次):

  File "c:\users\aquatrader\downloads\fingptselenium02.py", line 31, in <module>
    search2=driver.find_element(By.XPATH,'//*[@id="component-14"]')

  File "C:\Users\AquaTrader\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 831, in find_element
    return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]

  File "C:\Users\AquaTrader\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 440, in execute
    self.error_handler.check_response(response)

  File "C:\Users\AquaTrader\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\remote\errorhandler.py", line 245, in check_response
    raise exception_class(message, screen, stacktrace)

NoSuchElementException: Unable to locate element: //*[@id="component-14"]

~~~


Suggestions welcome. Thanks in advance.
python selenium-webdriver
1个回答
0
投票

您可以尝试在单击之前对清除按钮执行 WebdriverWait,并尝试使用 XPATH 而不是 CSS 选择器来查找股票输入框。

//div[@id='component-0']/label/textarea
© www.soinside.com 2019 - 2024. All rights reserved.