使用 browsermob 在 selenium 中声明窗口
我正在使用 browsermob 和 selenium 创建在网站上运行的脚本。我试图抓取页面上具有特定名称的所有元素。我的问题是当我尝试使用 window.document.getElementsByName("name");
browsermob 说 window
未定义。你如何定义窗口?
I am using browsermob and selenium for creating scripts to run on a site. I am trying to grab all of the elements on the page with a certain name. My problem is when I try to use window.document.getElementsByName("name");
browsermob says that window
is not defined. How do you define window?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要调用 selenium.getEval()。该调用的签名是它接受一个字符串参数,该参数是将在浏览器中执行的 JavaScript,并返回一个字符串,即字符串表示形式返回的结果。
最后一部分——字符串表示——很重要。虽然您当然不能在 BrowserMob 脚本中执行此操作:
您也不能执行此操作:
虽然第二个示例更接近您需要执行的操作,但它不太有效,因为 getElementsByName 返回一个 DOM 对象数组,该数组获取转换为字符串。相反,您很可能需要决定要对这些元素执行什么操作,并创建一个更大的 JS 片段来 eval,以准确返回您想要的内容。
例如,这将返回页面中第二个链接的 href 属性:
我希望有帮助。您需要了解的主要事情是,虽然 BrowserMob 脚本可以用 JavaScript 编写,但它运行的 JavaScript 环境不在浏览器中。要在浏览器中评估任意 JavaScript,您必须通过 getEval(),从而造成一种 JavaScript-in-JavaScript 的情况,这可能会有点令人困惑。
You need to call selenium.getEval(). The signature of that call is that it takes a string argument, which is the JavaScript that will be executed in the browser, and it returns a string, which is the string representation of the returned results.
That last part - the string representation - is important. While you certainly can't do this in your BrowserMob script:
You also can't do this:
While that second example is closer to what you need to do, it's not quite going to work because getElementsByName returns an array of DOM objects that get converted in to a string. Instead, you most likely need to decide what you want to do with those elements and create a larger JS snippet to eval that returns exactly what you want.
For example, this will return the href attribute of the second link in the page:
I hope that helps. The main thing you need to understand is that while BrowserMob scripts can be written in JavaScript, that JavaScript environment that it runs in is not in the browser. To evaluate arbitrary JavaScript in the browser, you must go through getEval(), thus creating a bit of a JavaScript-in-JavaScript situation that can get a little confusing.