Selenium中的iFrames问题
我正在尝试使用Selenium(用Python写的)来抓取一个几乎完全由JavaScript构成的网页。
比如,这就是页面的主体部分:
<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?
1 个回答
iframe 就像是独立的小网页,所以你不能直接在主页面的 HTML 代码里看到它们的内容;你需要单独去读取它们。
你可以使用 Selenium 的 select_frame
函数来做到这一点。
你可以通过 iframe 的名字、CSS 选择器、xpath 路径等方式来访问它,就像访问其他元素一样。
当你选择了一个 iframe 后,Selenium 的上下文就会改变,这样你就可以像在当前页面一样访问这个 iframe 的内容。
如果你有嵌套的 iframe,你可以继续这个过程,逐层向下访问。
当然,你需要一种方法来返回到上层的 iframe。Selenium 提供了这个功能,你可以使用同样的 select_frame
函数,传入参数 relative=up
来返回到当前 iframe 的父级,或者 relative=top
来返回到浏览器的主页面。
所以通过这个函数,你可以在页面中的不同 iframe 之间导航。
你不能一次性访问所有的 iframe;一次只能有一个 iframe 在上下文中,所以你不能通过一次 get_html_source
调用来获取所有 iframe 的内容,但你可以在你的 Selenium 脚本中逐个访问这些 iframe,并分别获取每个 iframe 的 HTML 源代码。
希望这能帮到你。