使用 browsermob 在 selenium 中声明窗口

发布于 2024-09-15 07:29:45 字数 180 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云裳 2024-09-22 07:29:45

您需要调用 selenium.getEval()。该调用的签名是它接受一个字符串参数,该参数是将在浏览器中执行的 JavaScript,并返回一个字符串,即字符串表示形式返回的结果。

最后一部分——字符串表示——很重要。虽然您当然不能在 BrowserMob 脚本中执行此操作:

var elements = window.document.getElementsByName("name");

您也不能执行此操作:

var elements = selenium.getEval('return window.document.getElementsByName("name")');

虽然第二个示例更接近您需要执行的操作,但它不太有效,因为 getElementsByName 返回一个 DOM 对象数组,该数组获取转换为字符串。相反,您很可能需要决定要对这些元素执行什么操作,并创建一个更大的 JS 片段来 eval,以准确返回您想要的内容。

例如,这将返回页面中第二个链接的 href 属性:

var secondHref = selenium.getEval('return window.document.getElementsByName("a")[1].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:

var elements = window.document.getElementsByName("name");

You also can't do this:

var elements = selenium.getEval('return window.document.getElementsByName("name")');

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:

var secondHref = selenium.getEval('return window.document.getElementsByName("a")[1].href');

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文