使用 cheerio 获取属性列表
use cheerio to get a list of attributes
我想从以下字符串中获取 ['http://www.1.com', 'http://www.2.com', 'http://www.3.com']
。
const cheerio = require('cheerio')
const htmlStr = `
<div>
<div class="item">
<a href="http://www.1.com"></a>
</div>
<div class="item">
<a href="http://www.2.com"></a>
</div>
<div class="item">
<a href="http://www.3.com"></a>
</div>
</div>
`
const $ = cheerio.load(htmlStr)
最初,我以为 $(div.item a)
会 return 一个元素数组。所以我尝试了 :
const urls = $('div.item a').map(x => x.attr('href'))
失败了。
似乎 $('div.item a')
return 是 object
。
怎么做?
谢谢!
首先,cheerio 的 map
函数接受回调,其中第一个参数是当前 index,而不是再次必须包含在 [=12= 中的元素].接下来,map
returns 一个 "jQuery set",而不是普通的 JavaScript 数组。使用 toArray
:
$('div.item a').map((i, x) => $(x).attr('href')).toArray()
另想办法:
$('div.item a').get().map(x => $(x).attr('href'))
get()
检索所有匹配的元素。
我想从以下字符串中获取 ['http://www.1.com', 'http://www.2.com', 'http://www.3.com']
。
const cheerio = require('cheerio')
const htmlStr = `
<div>
<div class="item">
<a href="http://www.1.com"></a>
</div>
<div class="item">
<a href="http://www.2.com"></a>
</div>
<div class="item">
<a href="http://www.3.com"></a>
</div>
</div>
`
const $ = cheerio.load(htmlStr)
最初,我以为 $(div.item a)
会 return 一个元素数组。所以我尝试了 :
const urls = $('div.item a').map(x => x.attr('href'))
失败了。
似乎 $('div.item a')
return 是 object
。
怎么做?
谢谢!
首先,cheerio 的 map
函数接受回调,其中第一个参数是当前 index,而不是再次必须包含在 [=12= 中的元素].接下来,map
returns 一个 "jQuery set",而不是普通的 JavaScript 数组。使用 toArray
:
$('div.item a').map((i, x) => $(x).attr('href')).toArray()
另想办法:
$('div.item a').get().map(x => $(x).attr('href'))
get()
检索所有匹配的元素。