【问题标题】:How to access a piece of embedded JS?如何访问一段嵌入式 JS?
【发布时间】: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


【解决方案1】:

首先,用$('script').text()获取脚本标签的内容。如果页面上有更多脚本标签,您可能需要调整选择器。然后用正则匹配你要访问的数组:

const script = $('script').text();
const [, arrStr] = script.match(/sports:\s+(\[[\s\S]+\])/);

最后,使用eval将字符串转为数组:

const arr = eval(arrStr);

demo

【讨论】:

    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 2014-01-20
    • 2019-08-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多