Skip to main content
 首页 » 编程设计

python之在 selenium 网络驱动程序中如何选择正确的 iframe

2025年02月15日15JustinYoung

我正在尝试点击此页面上的一个元素:

url = 'https://finance.yahoo.com/quote/GOOG?ltr=1' 
driver = webdriver.Firefox() 
driver.get(url) 
driver.find_element_by_link_text('Financials') 

此时我想单击“现金流”、“ Assets 负债表”或“季度”。我知道这些按钮已加载,因为我可以使用 BeautifulSoup 从页面源中提取它们。但是当我尝试使用 Selenium 时:

driver.find_element_by_link_text('Cash Flow') 
driver.find_element_by_link_text('Balance Sheet') 
driver.find_element_by_link_text('Quarterly') 

除“Quarterly”外,所有返回“Unable to locate element”都返回一个元素,但它是位于图表上方的元素,而不是我感兴趣的表格上方的元素。

我认为这是因为在错误的 iframe 中,我已经找到了所有的 iframe:

driver.find_elements_by_tag_name('iframe') 

返回 9 个元素。但是我无法确定我要单击的元素属于哪个 iframe。我也按顺序浏览了 iframe,但仍然找不到我感兴趣的元素。

请您参考如下方法:

我刚刚检查了网站,它们(您要查找的元素)不在任何 iframe 标记中。

以下代码对我有用(更改为 xpath,无需切换):

driver.find_element_by_xpath("//span[contains(text(),'Cash Flow')]").click() 
driver.find_element_by_xpath("//span[contains(text(),'Balance Sheet')]").click() 
driver.find_element_by_xpath("//span[contains(text(),'Quarterly')]").click() 

注意:可能是因为对于“Financials”,父标签是a,代表一个链接,但对于其他元素(Cash Flow,Balance sheet) ,父标记是 div ,它不是链接标记。所以 find_element_by_link_text 可能不起作用。


在 iframe 之间切换:

在我们尝试识别它之前,您必须切换到元素所在的框架。

假设,您的元素位于 3 个 iframe 中,如下所示:

<iframe name="frame1"> 
  <iframe name="frame2"> 
     <iframe name="frame3"> 
        <span>CashFlow</span> <! Span element is inside of 3 iframes> 
    </iframe> 
    <span>balance sheet> <! Span element is inside of 2 iframes> 
  </iframe> 
</iframe> 

现在,如果您想识别三个 iFrame 中的 CashFlow:

    driver.switch_to_frame(driver.find_element_by_name("frame1")) // here, you can provide WebElement representing the iFrame or the index. 
    driver.switch_to_frame(driver.find_element_by_name("frame2")) 
    driver.switch_to_frame(driver.find_element_by_name("frame3")) 
    driver.find_element_by_link_text("CachFlow") 
 
    # switch to default frame before you again try find some other element which is not in the same frame (frame3) 
 
   driver.switch_to_default_content() 
 
   # then navigate to the frame that you want to indentify the element: 
   driver.switch_to_frame(driver.find_element_by_name("frame1"))  
   driver.switch_to_frame(driver.find_element_by_name("frame2")) 
   driver.find_element_by_link_text("balance sheet") 
 
  # switch to default content again 
  driver.switch_to_default_content() 

注意:我使用了框架引用而不是索引,因为您提到有 9 个 iFrame。因此,使用索引会造成混淆。如果您无法识别 frameElement,则只能使用索引。

引用:

  1. http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.switch_to_frame