【问题标题】:Problem with iFrames in SeleniumSelenium 中的 iFrame 问题
【发布时间】:2011-09-15 21:03:54
【问题描述】:

我正在尝试使用几乎完全是 Javascript 的 Selenium(在 Python 中)抓取网页。
例如,这是页面的正文:

<body class="bodyLoading">
<!-- this is required for GWT history support -->
<iframe id="__gwt_historyFrame" role="presentation" width="0" height="0" tabindex="-1" title="empty" style="position:absolute;width:0;height:0;border:0" src="javascript:''">  </iframe>
<!-- For printing window contents  -->
<iframe id="__printingFrame" role="presentation" width="0" height="0" tabindex="-1" title="empty" style="width:0;height:0;border:0;"   />


<!-- TODO : RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
 Your web browser must have JavaScript enabled in order for
 Regulations.gov to display correctly.
</div>
</noscript>
</body>

由于某种原因,selenium(使用 Firefox 引擎)不会评估此页面上的 javascript。如果我使用 get_html_source 函数,它只会返回上面的 html,而不是我可以在浏览器(和 Selenium 浏览器)中看到的 JavaScript 导入的 HTML。而且,不幸的是,我无法从 iFrame 中找出 src 属性,只是说 javascript: 我无法弄清楚。

关于如何确保 Selenium 处理这个 iFrame 有什么想法吗?

【问题讨论】:

  • 您能否发布您的 selenium 驱动程序代码 - 例如,您是否允许有足够的时间来加载页面(selenium 是异步的等等)

标签: python iframe selenium


【解决方案1】:

iframe 是单独的文档,因此您不会将它们的内容包含在主页的 HTML 代码中;您必须单独阅读它们。

您可以使用 Selenium 的 select_frame 函数来做到这一点。

您可以通过框架名称、CSS 选择器、xpath 引用等访问框架,与其他元素一样。

当您选择框架时,您会更改 Selenium 的上下文,因此您可以像访问当前页面一样访问框架的内容。

如果框架中有框架,则可以通过框架树继续此过程。

显然,您需要一种返回帧路径的方法。 Selenium 通过允许您使用相同的select_frame 函数来提供此功能,使用参数relative=up 将上下文移动到当前框架的父级,或relative=top 移动到浏览器中的主页。

因此,使用此功能,您可以浏览页面中的框架。

您不能同时访问它们;一次只能在上下文中使用一个框架,因此您将永远无法进行单个 get_html_source 调用并一次获取所有框架的内容,但是您可以在 Selenium 脚本中浏览页面中的框架并获取每个框架的 HTML 源代码。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2020-10-06
    • 2017-03-28
    相关资源
    最近更新 更多