我正在使用 cheerio
,我如何获得 content
?
我的代码对此很oke:
request('https://example.com', function (error, response, html) {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);
console.log(html);
}
});
我需要从content
获得사이드
:
<meta property="og:description" content="👤 I'm Jack">
<meta property="og:title" content="사이드"> // How to Get `사이드` and print in console.log?
request('https://example.com', function (error, response, html) {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);
console.log($("meta[property='og:title']").attr("content"));
}
});
侧节点(与答案中的以前错误有关):
使用Cheerio时,您应该意识到它仅模拟jQuery API的某些方面,并且不会重新创建整个DOM。这意味着与以前版本的答案相反,您不能做:
$("meta").get(1).getAttribute("origin");
将导致试图致电undefined
的TypeError。Cheerio建立了实施jQuery API子集的DOM的代表。get
API存在,但将返回此表示形式,而不是标准DOM ONE,并且getAttribute
没有附加在Cheerio表示形式上。如果您想要完整的DOM表示和jQuery,则需要使用 jsdom 。
第一种方法: console.log($("meta[property='og:title']").attr("content"));
由 @adz5a
SECEND Way: console.log($("meta").eq(1).attr("content"));
.get()
返回一个dom对象。
Cheerio不是浏览器,因此不可用DOM API。