selenium.common.exceptions.TimeoutException:当我尝试使用python进行按钮单击时,将出现此错误

时间:2018-11-27 05:58:39

标签: python selenium selenium-webdriver iframe webdriverwait

我正在使用Selenium软件包来单击某个网站的按钮。当我尝试时出现以下错误:

selenium.common.exceptions.TimeoutException: Message:

这是尝试运行的代码。

import time 
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 bs4 import BeautifulSoup as BSoup
from datetime import date, timedelta
import pyodbc 
import datetime

browser =  webdriver.Firefox()
browser.get("https://www.cbsl.gov.lk/rates-and-indicators/exchange-rates/daily-buy-and-sell-exchange-rates")
#time.sleep(10)

#browser.find_element_by_xpath('//*[@id="dailyexchange"]/div[2]/div/button[1]').click()

wait = WebDriverWait(browser, 20)
element = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="dailyexchange"]/div[2]/div/button[1]')))
element.click()

2 个答案:

答案 0 :(得分:1)

在点击按钮之前,您需要切换到iframe:

browser.get("https://www.cbsl.gov.lk/rates-and-indicators/exchange-rates/daily-buy-and-sell-exchange-rates")
wait = WebDriverWait(browser, 20)
wait.until(EC.frame_to_be_available_and_switch_to_it('iFrameResizer2'))
element = wait.until(EC.element_to_be_clickable((By.NAME, 'select_button')))
element.location_once_scrolled_into_view
element.click()

答案 1 :(得分:-1)

所需元素位于<iframe>中,因此您必须:

  • 诱导 WebDriverWait 以使所需的框架可用并切换到它。
  • 诱导 WebDriverWait 以使所需的元素可点击
  • 您可以使用以下任一解决方案:

    • 使用CSS_SELECTOR

      from selenium import webdriver
      from selenium.webdriver.chrome.options import Options
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      
      options = Options()
      options.add_argument("start-maximized")
      browser = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
      browser.get("https://www.cbsl.gov.lk/rates-and-indicators/exchange-rates/daily-buy-and-sell-exchange-rates")
      WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#iFrameResizer2[src='/cbsl_custom/exratestt/exratestt.php']")))
      WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-default[name='select_button']"))).click()
      
    • 浏览器快照:

selectall