1

我正在使用 browsermob 和 selenium 创建要在站点上运行的脚本。我正在尝试使用特定名称获取页面上的所有元素。我的问题是当我尝试使用window.document.getElementsByName("name");browsermob 时说window没有定义。你如何定义窗口?

4

1 回答 1

3

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.

于 2010-08-19T15:24:28.950 回答