使用python硒从iframe中的列表中选择元素

时间:2019-07-12 10:29:17

标签: python selenium iframe

我想编写一个python程序,该程序从网页自动下载历史股票数据。我要选择的元素的相应HTML代码在下面的图片上:

有两个iframe。一个在另一个里面。我切换到第二个iframe,但是找不到想要单击的元素。我收到以下错误:“消息:没有这样的元素:无法找到元素:{”方法“:” css选择器“,”选择器“:” [id =“:cu”]“}(会话信息:chrome = 75.0 .3770.100)”


from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import ctypes  # An included library with Python install.   
import time

user = ""
pwd = ""
driver = webdriver.Chrome()
driver.get("https://www.dukascopy.com/trading-tools/widgets/quotes/historical_data_feed")
driver.maximize_window()

## Give time for iframe to load ##
time.sleep(1)

# get the list of iframes present on the web page using tag "iframe"
seq = driver.find_elements_by_tag_name('iframe')
print("No of frames present in the web page are: ", len(seq))

#switch to correct iFrame
driver.switch_to_default_content()
iframe = driver.find_elements_by_tag_name('iframe')[1]
driver.switch_to.frame(iframe)

driver.implicitly_wait(5)

elem = driver.find_element_by_id(':cu')
elem.click()

ctypes.windll.user32.MessageBoxW(0, "Test", "Test MsgBox", 1)

driver.close()

如果我的代码正确无误,则会选择列表中的“ EUR / TRY”元素。

1 个答案:

答案 0 :(得分:0)

共有4个iframe。

您要与之交互的表位于iframe[src^='https://freeserv']中,父iframe为widget-container。您必须像这样一个接一个地切换到它:

代码:

wait = WebDriverWait(driver,10)

driver.maximize_window()

driver.get("https://www.dukascopy.com/trading-tools/widgets/quotes/historical_data_feed")

wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "widget-container")))

wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src^='https://freeserv']")))

check_Box = wait.until(EC.visibility_of_element_located((By.XPATH, "//strong[text()='EUR/TRY']/../preceding-sibling::span/span")))
ActionChains(driver).move_to_element(check_Box).perform()
check_Box.click()