如何通过 Python 使用 Selenium WebDriver 在 iframe 中定位元素

How to locate the element within an iframe using Selenium WebDriver through Python

在本网站上进行自动化测试时 http://www.scstrade.com/TechnicalAnalysis/tvchart/ 我无法使用 selenium 找到该元素。

我想在顶部找到用于搜索股票的搜索栏元素,然后使用 selenium 在该栏中传递所需股票的名称。
这是搜索栏的 xpath:

/html/body/div[1]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div/div/input

这是我的代码:

from selenium import webdriver
driver = webdriver.Chrome("D:\PyCharm Projects\Web Automation\drivers\chromedriver.exe")
driver.get("http://www.scstrade.com/TechnicalAnalysis/tvchart/")
driver.find_elements_by_xpath('/html/body/div[1]/div[2]/div/div/div[1]/div/div/div/div/div[1]/div/div/input')
Output : []

我还尝试使用 class 名称查找元素:

driver.find_element_by_class_name('input-3lfOzLDc-')

这给了我这个错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"input-3lfOzLDc-"}
  (Session info: chrome=83.0.4103.61)
  (Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Windows NT 10.0.17134 x86_64)

我尝试访问的元素只有 class 名称,所以我无法尝试使用该 ID。 我也尝试先切换到框架,但我什至无法使用 selenium 找到该网站的框架元素。

左上角的搜索栏元素在 <iframe> 中,因此要在该元素上调用 send_keys(),您必须:

  • 为所需的 frame_to_be_available_and_switch_to_it().
  • 引入 WebDriverWait
  • 为所需的 element_to_be_clickable().
  • 引入 WebDriverWait
  • 您可以使用以下任一项:

    • 使用CSS_SELECTOR:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='charting_library/static/en-tv-chart']")))
      index = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#header-toolbar-symbol-search input")))
      index.click()
      index.clear()
      index.send_keys("KSE 30")
      
    • 使用XPATH:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@src, 'charting_library/static/en-tv-chart')]")))
      index = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='header-toolbar-symbol-search']//input")))
      index.click()
      index.clear()
      index.send_keys("KSE 30")
      
  • 注意:您必须添加以下导入:

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

参考资料

您可以在以下位置找到一些相关讨论:

  • Switch to an iframe through Selenium and python