使用 By.LINK_TEXT 单击页面上的特定按钮,但 find_element 抛出异常

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

在此页面上:https://finance.yahoo.com/quote/KO/options

这个按钮是:

<button class="tertiary-btn fin-size-small menuBtn tw-justify-center rounded rightAlign svelte-xhcwo" data-ylk="elm:inpt;elmt:menu;itc:1;sec:qsp-options;slk:date-select;subsec:date" type="button" aria-label="May 24, 2024" aria-haspopup="listbox" data-type="date" data-rapid_p="14" data-v9y="1">
  <div class="icon fin-icon inherit-icn sz-medium svelte-21xhfv">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
      <path d="M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"></path>
    </svg>
  </div>
  <span class=" textSelect svelte-q648fa">May 24, 2024</span>
</button>

我尝试了这段代码:

browser = webdriver.Firefox()
browser.get("https://finance.yahoo.com/quote/KO/options")
# The option expiraiton date will change based on when this script runs 
option_expiration_date = "May 24, 2024"
wait = WebDriverWait(browser, 20)
field = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, option_expiration_date)))
elem = browser.find_element(By.LINK_TEXT, option_expiration_date)
elem.click()

但它抛出了这个异常:

Message=Message: 
Stacktrace:
RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8
WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:193:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:511:5
dom.find/</<@chrome://remote/content/shared/DOM.sys.mjs:136:16

  Source=C:\Users\Leave\source\repos\Selenium Demo\Selenium Demo\src\demoPackage\yahooFinance.py
  StackTrace:
  File "C:\Users\Leave\source\repos\Selenium Demo\Selenium Demo\src\demoPackage\yahooFinance.py", line 18, in yahooFinance
    field = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, option_expiration_date)))
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Leave\source\repos\Selenium Demo\Selenium Demo\src\mainPackage\main.py", line 17, in <module> (Current frame)
    yahooFinance()
selenium.common.exceptions.TimeoutException: Message: 
Stacktrace:
RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8
WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:193:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:511:5
dom.find/</<@chrome://remote/content/shared/DOM.sys.mjs:136:16
python selenium-webdriver
1个回答
0
投票

这是使用基于 XPATH 的定位器单击该按钮的方法:

//[... imports, define browser, etc ... make sure browser's window is tall enough, at least 1500px]

wait = WebDriverWait(driver, 15)
driver.get('https://finance.yahoo.com/quote/KO/options?guccounter=1')
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@name="agree"]'))).click()
driver.get('https://finance.yahoo.com/quote/KO/options?guccounter=1')
wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@aria-label="May 24, 2024"]'))).click()

Selenium 文档可以在这里找到。

© www.soinside.com 2019 - 2024. All rights reserved.