使用 cheerio 获取 html
Fetching html with cheerio
我正在使用 cheerio
,如何获取 content
?
我的代码对此没有问题:
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。这意味着与此答案的先前版本相反,您 cannot do :
$("meta").get(1).getAttribute("origin");
这将导致尝试调用 undefined
时出现 TypeError。 Cheerio 构建了 DOM 的表示,在其上实现了 jQuery api 的子集。 get
api 存在,但将 return 这种表示而不是标准的 DOM 表示,并且没有 getAttribute
方法附加到 cheerio 表示。如果你想要一个完整的 DOM 表示和 jQuery 你需要使用像 jsdom.
这样的东西
第一种方式: console.log($("meta[property='og:title']").attr("content"));
@adz5A
解决
第二种方式: console.log($("meta").eq(1).attr("content"));
.get()
returns 一个 DOM 对象。
Cheerio 不是浏览器,因此 DOM api 不可用。
我正在使用 cheerio
,如何获取 content
?
我的代码对此没有问题:
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。这意味着与此答案的先前版本相反,您 cannot do :
$("meta").get(1).getAttribute("origin");
这将导致尝试调用 undefined
时出现 TypeError。 Cheerio 构建了 DOM 的表示,在其上实现了 jQuery api 的子集。 get
api 存在,但将 return 这种表示而不是标准的 DOM 表示,并且没有 getAttribute
方法附加到 cheerio 表示。如果你想要一个完整的 DOM 表示和 jQuery 你需要使用像 jsdom.
第一种方式: console.log($("meta[property='og:title']").attr("content"));
@adz5A
第二种方式: console.log($("meta").eq(1).attr("content"));
.get()
returns 一个 DOM 对象。
Cheerio 不是浏览器,因此 DOM api 不可用。