使用浏览器在页面(客户端)上运行自定义JavaScript来模拟点击?怎么做?

Min*_* Yu 4 javascript browser ide console automation

我想自动从页面中抓取一些内容.

我想知道是否有可能:

  1. 在页面加载后在页面上运行我自己编写的JavaScript(我使用FireFox.我没有能力更改页面内容.我只想在浏览器上运行JS.).该脚本将使用getelementbyid或类似的方法来获取下一页的链接

  2. 运行JavaScript以在该页面上收集我感兴趣的内容(某些URL)并将这些URL存储在本地文件中

  3. 转到下一页(下一页将真正加载我的浏览器,但我根本不需要介入)并重复步骤1和步骤2,直到没有下一页.

这样做的经典方法是使用CURL等使用LWP或PHP脚本编写Perl脚本.但这就是服务器端.我想知道我是否可以做客户端.

Jer*_*her 5

实际上,我做了一些相似的事情.

通过使用GreaseMonkey,您可以编写一个用户脚本,该脚本将与您需要的页面进行交互.您可以获得下一页链接并根据需要滚动.

您还可以在Firefox中本地存储任何数据,但有一些新功能称为GM_getValue和GM_setValue.

我采取懒惰的方式.我只是生成了一个浏览页面时找到的URL列表.我做了一个原始的"document.write"方法,我将我的URL列表转储为一个规则的批处理文件wget.

此时,我复制并粘贴批处理文件,然后运行它.

如果您需要经常运行它以使其自动化,那么曾经有一种方法可以将GreaseMonkey脚本转换为可以获得更多功能的Firefox扩展.

另一种选择目前是AFAIK,仅限Chrome.您可以收集所需的任何信息并从中构建一个大文件,然后使用download链接的属性并单击以保存.

更新

我打算分享我正在做的完整代码,但是它与某个特定的网站紧密相关,它实际上没有帮助 - 所以我会寻求一个更"通用"的解决方案.

警告,此代码即时输入,可能实际上不正确.

// Define the container
// If you are crawling multiple pages, you'd want to load this from
// localStorage.
var savedLinks = [];

// Walk through the document and build the links.
for (var i = 0; i < document.links.length; i++) {
  var link = document.links[i];

  var data = { 
    url: link.url,
    desc = getText(link)
  };

  savedLinks.push(data);
}

// Here you'd want to save your data via localStorage.


// If not on the last page, find the 'next' button and load the next page
// [load next page here]

// If we *are* on the last page, use document.write to output our list.
// 
// Note: document.write totally destroys the current document.  It really is quite
// an ugly way to do it, but in this case it works.
document.write(JSON.stringify(savedLinks, null, 2));
Run Code Online (Sandbox Code Playgroud)