如何使用Node.js最有效地解析网页 [英] How to most efficiently parse a web page using Node.js

查看:163
本文介绍了如何使用Node.js最有效地解析网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析一个简单的网页并从html获取数据,例如src,data-attr等。如何使用Node.js最有效地完成这项工作?如果它有帮助,我正在使用Node.js 0.8.x。

I need to parse a simple web page and get data from html, such as "src", "data-attr", etc. How can I do this most efficiently using Node.js? If it helps, I'm using Node.js 0.8.x.

P.S。这是我正在解析的网站。我想得到一份当前曲目列表并制作我自己的html5应用程序,以便在移动设备上收听。

P.S. This is the site I'm parsing. I want to get a list of current tracks and make my own html5 app for listen on mobile devices.

推荐答案

我这样做了很多。如果您正在使用JavaScript的网站大量使用JavaScript,您将需要使用 PhantomJS 。请注意,PhantomJS不是Node.js.这是一个完全不同的JavaScript运行时。您可以通过 phantomjs-node node-phantom ,但他们都有点hacky。 YMMV与那些。避免与jsdom有任何关系。它会让你头疼 - 这包括 Zombie.js

I have done this a lot. You'll want to use PhantomJS if the website that you're scraping is heavily using JavaScript. Note that PhantomJS is not Node.js. It's a completely different JavaScript runtime. You can integrate through phantomjs-node or node-phantom, but they are both kinda hacky. YMMV with those. Avoid anything to do with jsdom. It'll cause you headaches - this includes Zombie.js.

你应该使用 Cheerio 请求。这对于大多数网页来说已经足够了。

What you should use is Cheerio in conjunction with Request. This will be sufficient for most web pages.

我写了一篇关于使用Cheerio请求的博客文章:使用Node.js快速和脏屏幕刮擦但是,如果它是JavaScript密集型,请使用PhantomJS与 CasperJS 一起使用。

I wrote a blog post on using Cheerio with Request: Quick and Dirty Screen Scraping with Node.js But, again, if it's JavaScript intensive, use PhantomJS in conjunction with CasperJS.

希望这会有所帮助。

使用请求和Cheerio的代码段:

Snippet using Request and Cheerio:

var request = require('request')
  , cheerio = require('cheerio');

var searchTerm = 'screen+scraping';
var url = 'http://www.bing.com/search?q=' + searchTerm;

request(url, function(err, resp, body){
  $ = cheerio.load(body);
  links = $('.sb_tlst h3 a'); //use your CSS selector here
  $(links).each(function(i, link){
    console.log($(link).text() + ':\n  ' + $(link).attr('href'));
  });
});

这篇关于如何使用Node.js最有效地解析网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆