【发布时间】:2011-10-30 07:30:23
【问题描述】:
我目前正在编写一个脚本来从 HTML 页面中抓取一些非常基本的信息。具体来说,我正在尝试从 allmusic.com 获取有关艺术家的一些信息。我正在使用 jQuery 在 node.js 中编写这个脚本来进行实际的抓取,并通过使用来自this blog post 的示例使其在一定程度上工作。
我要做的是搜索一位受欢迎的艺术家,然后在第一个结果中存储一些基本信息,这几乎完全是我正在寻找的艺术家。我可以使用下面的代码提取有问题的表格,但我不知道如何从 HTML 中获取前几个 td 元素,这是我真正需要做的。我的node.js代码如下:
var request = require('request'),
jsdom = require('jsdom');
request({ uri:'http://allmusic.com/search/artist/lady+gaga' }, function (error, response, body) {
jsdom.env({
html: body,
scripts: [
'http://code.jquery.com/jquery-1.5.min.js'
]
}, function (err, window) {
var $ = window.jQuery;
// jQuery is now loaded on the jsdom window created from 'agent.body'
var search = $('.search-results').html();
if(search != null){
//gah what can i do here?!?
}
});
});
下面是有问题的 HTML 块,所以你不需要自己去寻找它:
<table class="search-results" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<th class="relevance">
<a href="http://www.allmusic.com/search/artist/lady gaga/filter:all/exact:0/order:relevance-asc" title="order by relevance">Relevance</a>
</th>
<th width="10px"> </th>
<th>
<a href="http://www.allmusic.com/search/artist/lady gaga/filter:all/exact:0/order:name-asc" title="order by name">Name</a>
</th>
<th width="75px">
<a href="http://www.allmusic.com/search/artist/lady gaga/filter:all/exact:0/order:genre-asc" title="order by genre">Genre</a>
</th>
<th width="200px">Years Active</th>
</tr>
ACTUAL RELEVANT STUFF THAT I WANT ARE BELOW
<tr>
<td class="relevance text-center">
<div class="bar" style="width:100%" title="100%"></div>
</td>
<td class="text-center"></td>
<td><a href="http://www.allmusic.com/artist/lady-gaga-p1055684">Lady Gaga</a></td>
<td>Pop/Rock</td> //SPECIFICALLY THIS
<td>00s</td>
</tr>
此表中有更多条目,但这是第一个结果。是否可以创建一个 td 数组或类似的东西并获得正确的索引?假设我总是会得到第一个结果,那么每个艺术家的索引应该是相同的。
如果这不可能,还有其他方法可以实现我的目标吗?或者,有没有更好的方法来做我想要用 node.js 做的事情?我查看了一堆不同的选项,这似乎是最简单的。
最好的,谢谢,
萨米
【问题讨论】:
标签: jquery node.js jquery-selectors screen-scraping web-scraping