如何在Python Selenium中找到嵌入在iframe中的元素

时间:2016-03-24 05:45:27

标签: python selenium

我在查找iframe中嵌入的单个报表元素时遇到问题。表格中包含许多报告,其中包含iframe。另外使用firefox firePath它给了我一个非常链接,我不知道如何删除长字符串。编辑了代码:

    browser.switch_to_frame(browser.find_element_by_tag_name("iframe"))
    # set the context on the child frame
    browser.switch_to_frame(browser.find_element_by_id("__gwt_historyFrame"))

    # set the context on the next child frame
   wait = WebDriverWait(self.browser, 10)
        browser.switch_to_frame(wait.until(EC.presence_of_element_located(By.ID,"com.demandreports.wb.Workbench")))

    #click the link
    wait.until(EC.presence_of_element_located(By.LINK_TEXT,"Invoice Aging Report")).click()

    # switch back to the main document context
    browser.switch_to_default_content()

这是错误:

    Traceback (most recent call last):
  File "C:\Python34\zuoraDataexport6.py", line 118, in <module>
    scraper.scrape()
  File "C:\Python34\zuoraDataexport6.py", line 57, in scrape
    browser.switch_to_frame(browser.find_element_by_id("com.demandreports.wb.Workbench"))
  File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 234, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 712, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
  File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"com.demandreports.wb.Workbench"}

这就是我想要找到的:     发票账龄报告

这是html:

<document>
    <html style="overflow: hidden;">
    <head>
    <body style="margin: 0px;">
    <iframe id="__gwt_historyFrame" style="position:absolute;width:0;height:0;border:0" tabindex="-1" src="javascript:''"/>
    <iframe id="com.demandreports.wb.Workbench" src="javascript:''" style="position: absolute; width: 0px; height: 0px; border: medium none;" tabindex="-1"/>
    <table class="Workbench-Page" cellspacing="0" cellpadding="0">
    <tbody>
    <tr>
    <tr>
    <tr>
    </tbody>
    </table>
    </body>
    </html>
</document>

1 个答案:

答案 0 :(得分:0)

未在元素所在的帧上设置上下文。您需要切换到树线上的每个帧:

# set the context on the child frame
browser.switch_to_frame(browser.find_element_by_id("__gwt_historyFrame"))

# set the context on the next child frame
browser.switch_to_frame(browser.find_element_by_id("com.demandreports.wb.Workbench"))

#click the link
wait.until(EC.presence_of_element_located(By.LINK_TEXT,"Invoice Aging Report")).click()

# switch back to the main document context
browser.switch_to_default_content()