【问题标题】:Scraping with node.js and jquery使用 node.js 和 jquery 进行抓取
【发布时间】:2021-04-02 23:21:23
【问题描述】:

我正在尝试按照本教程学习如何使用 node 和 jquery 进行抓取 -

http://net.tutsplus.com/tutorials/javascript-ajax/how-to-scrape-web-pages-with-node-js-and-jquery/

在其中他们有一些这样的代码 -

request({uri:"http://events.sfgate.com/search?swhat=&swhen=&swhere=San+Francisco&commit=Search&st_select=any&search=true&svt=text&srss="},function(err,response,body){

jsdom.env({
html: "http://events.sfgate.com/search?swhat=&swhen=&swhere=San+Francisco&commit=Search&st_select=any&search=true&svt=text&srss=",
src:['http://code.jquery.com/jquery-1.6.min.js'],
done: function(errors,window){
    console.log("WINDOW");
    console.log(window.jQuery);
    var $ = window.$;
    //other stuff

当我控制台记录window.jquery 或window.$ 时,两者都未定义——但它们不应该是因为jsdom 应该将jquery 嵌入到页面中吗?为什么这没有发生?

【问题讨论】:

    标签: javascript node.js jsdom


    【解决方案1】:

    问题在于您使用“src”参数对其进行了初始化,该参数应包含 javascript 文件(在本例中为 jquery)的实际源代码数组 - 而不是文件的 url。

    如果你想要 url,你需要像这样初始化它:

    jsdom.env(
      "http://nodejs.org/dist/",
      ["http://code.jquery.com/jquery.js"],
      function (errors, window) {
    

    或者像这样:

    jsdom.env({
      html: "http://news.ycombinator.com/",
      scripts: ["http://code.jquery.com/jquery.js"],
      done: function (errors, window) {
    

    编辑: 您的代码中还有另一个错误(如果我没记错的话......) - 您首先使用 request 模块下载页面,然后将 html 源代码传递给 jsdom(通过传递它body 你从 request 得到的)你告诉 jsdom 再次下载页面。如果你给 jsdom 页面的 url 作为 html 那么你不需要调用 request 模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-26
      • 2017-06-23
      • 2010-12-28
      • 1970-01-01
      • 2020-04-27
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多