【发布时间】:2019-02-20 19:06:36
【问题描述】:
我正在尝试使用 Cheerio 抓取一些网站,但是由于该应用程序是动态的,因此内容不存在于 HTML 中,而是存在于我不知道如何访问的 JS 对象上(我尝试过窗口、文档等)
我的代码:
let axios = require('axios') // HTTP client
let cheerio = require('cheerio') // HTML parsing package
const url = 'https://www.foo.com'
const getWebsiteContent = async (url) => {
try {
const response = await axios.get(url)
const $ = cheerio.load(response.data)
console.log(response.data)
} catch (error) {
console.error(error)
}
}
getWebsiteContent(url)
console.log 的结果(我只是粘贴我需要访问的部分):
<!DOCTYPE html>
<html lang='en' ng-app='Test'>
<head>
</head>
<body class='' data-allow-utf8='false'>
<h1>HEADER</h1>
<script>
var matchData = function () {
Live.load.main({
version: "1.2",
sports: [
{
title: 'matchone',
subtitle: 'foo'
},
{
title: 'matchtwo',
subtitle: 'aaa'
}
],
})
}
</script>
<!-- More stuff -->
</body>
</html>
我要访问的数据是 sports 数组,包含在 matchData 函数内的 Live.load.main 方法中。
我什至不确定 Cheerio 是否是正确的工具,因为我希望数据位于一段 HTML 中,但显然是以某种方式加载的,我只能在触发 GET 请求时在 JS 对象中看到它。
【问题讨论】:
标签: javascript html node.js cheerio