使用 PhantomJS 获取 JSON 页面内容

发布于 2024-12-27 08:33:42 字数 188 浏览 6 评论 0原文

我想知道如何在 phantomjs 中解析 JSON。任何页面内容都包含在 html 中 (

{JSON string}
)。是否有选项可以删除封闭标签或要求使用不同的内容类型作为“application/json”?如果没有,解析它的最佳方法是什么。包含 includeJS jQuery 后是否使用 jQuery?

I would like to know how to parse JSON in phantomjs. Any page content is enclosed in html (<html><body><pre>{JSON string}</pre></body></html>). Is there an options to remove enclosing tags or asking for a different Content-Type as "application/json"? If not, what's the best way to parse it. Is it using jQuery after including with includeJS jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

好倦 2025-01-03 08:33:42

由于您使用的是由 webkit 浏览器构建的 PhantomJS,因此您可以访问本机 JSON 库。无需使用 page.evaluate,只需使用页面对象上的 plainText 属性即可。

http://phantomjs.org/api/webpage/property/plain-text.html

var page = require('webpage').create();
page.open('http://somejsonpage.com', function () {
    var jsonSource = page.plainText;
    var resultObject = JSON.parse(jsonSource);
    phantom.exit();
});

Since you are using PhantomJS which is built of the webkit browser you have access to the native JSON library. There is no need to use page.evaluate, you can just use the plainText property on the page object.

http://phantomjs.org/api/webpage/property/plain-text.html

var page = require('webpage').create();
page.open('http://somejsonpage.com', function () {
    var jsonSource = page.plainText;
    var resultObject = JSON.parse(jsonSource);
    phantom.exit();
});
疑心病 2025-01-03 08:33:42

这就是我所做的:

var obj = page.evaluate(function() {
    return eval('(' + document.body.innerText + ')');
}

然后你得到的 obj 就是从该页面返回的 JSON 对象。

Here is what I did:

var obj = page.evaluate(function() {
    return eval('(' + document.body.innerText + ')');
}

Then the obj you got is the JSON object returned from that page.

百思不得你姐 2025-01-03 08:33:42

正如已接受的答案中所述,我建议使用 JSON.parse() 将 JSON 字符串转换为对象。

例如,您的代码可能如下所示:

var jsonObject = page.evaluate(function() {
  return JSON.parse(page.plainText);
});

As already in the accepted answer, I would suggest using JSON.parse() for converting a JSON string into an object.

For example, your code could look like this:

var jsonObject = page.evaluate(function() {
  return JSON.parse(page.plainText);
});
少女的英雄梦 2025-01-03 08:33:42

如果 json 数据包含 html 字符串,它们将在建议的 page.plainText 属性中被删除。

If the json data contains html strings, they will be removed within the suggested page.plainText attribute.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文