javascript 使用cheerio检索href
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25438048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
href retrieval with cheerio
提问by sivanes
I have a downloaded html file that looks something like this
我有一个下载的 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">
I need to get to each of the <tr class="trodd">
and <tr class="treven">
entries of the table user_list
and retrieve the href. This is the code I have now and it returns just an empty array. One of the things I can't get a grasp on is whether cheerio is capable of finding each class="list_album"
like this or you have to make your way down the file's hierarchy with a bunch of $( )
's.
我需要访问表的每个<tr class="trodd">
和<tr class="treven">
条目user_list
并检索href。这是我现在拥有的代码,它只返回一个空数组。我无法理解的一件事是,cheerio 是否能够找到这样的每一个,class="list_album"
或者您必须使用一堆$( )
's沿着文件的层次结构向下移动。
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);
回答by Ja. L
I did this and it worked for me:
我这样做了,它对我有用:
Make sure to use $(value)
instead of $(this)
确保使用$(value)
而不是$(this)
$('.list_album').each( (index, value) => {
var link = $(value).attr('href');
links.push({"link": link});
});
回答by rffaguiar
I don't have enough reputation to comment, so I will answer here. It seems a typo, the 'dot' on selector and the $ wrapper. Try this.
我没有足够的声誉发表评论,所以我会在这里回答。这似乎是一个错字,选择器上的“点”和 $ 包装器。试试这个。
$('.list_album').each( function () {
var link = $(this).attr('href');
links.push({"link": link});
});
回答by kapil
I dont have reputation to comment but may help someone.OP did not add dot in given snippet.
instead of $('list_album')
, you need to use $('.list_album')
.Here dot operator is class selector.
我没有评论的声誉,但可能会帮助某人。OP 没有在给定的代码段中添加点。而不是$('list_album')
,您需要使用。$('.list_album')
这里点运算符是类选择器。