我下载了一个看起来像这样的 html 文件
<html class="theme_">
<head>
<body>
<div id="ad_1"></div>
...
<div id="wrapper">
<div id="top" style="height:11px;color:white;font-size:9px;font-weight:bold;"> </div>
...
<div id="content" style="border-top:none;">
...
<table id="user_list">
<tbody>
<tr class="trodd">
<td width="10%" valign="center" align="center">
<td class="list_art" style="width:160px;">
<td class="main_entry">
<h4>
<h5>
<a class="list_album" href="https://rateyourmusic.com/release/single/electra__ita_/feels_good__carrots_and_beets_/" title="[Album833409]">Feels Good (Carrots & Beets)</a>
<span class="rel_date">(1982) [Single]</span>
</h5>
</td>
<td></td>
</tr>
<tr class="treven">
我需要到达每个 <tr class="trodd">
和 <tr class="treven">
表的条目 user_list
并检索 href。这是我现在的代码,它只返回一个空数组。我无法掌握的一件事是 cheerio 是否能够找到每个 class="list_album"
像这样,否则您必须使用一堆 $( )
沿着文件的层次结构向下移动的。
var cheerio = require("cheerio");
var file = "...path...";
var links = [];
var $ = cheerio.load(file);
$('list_album').each( function () {
var link = $(this.attr('href'));
links.push({"link": link});
});
console.log(links);
最佳答案
我这样做了并且对我有用:
确保使用 $(value)
而不是 $(this)
$('.list_album').each( (index, value) => {
var link = $(value).attr('href');
links.push({"link": link});
});
关于javascript - 使用 cheerio 检索 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25438048/