【问题标题】:Parse web page content, not source code解析网页内容,而不是源代码
【发布时间】:2014-04-02 13:53:29
【问题描述】:

我正在开发一个 android 项目,我从网络流中收集数据并在应用程序中使用它。另一位成员正在该项目的 Web 端工作,该项目将我正在使用的数据推送到网页以供我收集。

数据是 JSON 格式,我编写了一个解析器,可以根据需要解析数据。问题是,当我连接到我想要的 URL 时,我无法从中获取 JSON 数据。

网页的用户界面显示了我需要的 JSON,但它不在源代码中。当我抓取网页时,我得到的只是没有数据的源代码 这是我要连接的 URL:

http://ec2-54-194-27-150.eu-west-1.compute.amazonaws.com:8080/eirwig-spring-mvc/tweeter-single

这是我需要的示例显示:

{ "id": "451355222041182208", 
  "text": "And @Andrewgobrien_ !", 
  "user": "darraghosulliv4", 
  "profileImageUrl": "http://pbs.twimg.com/profile_images/441638045100834816/8xZggJsT_normal.jpeg", 
  "con": "Ireland", 
  "lat": 51.86972925, 
  "lng": -8.42925046, 
  "countries": {"United Kingdom":2442,"Ireland":8401}, "tweetCount": 10843 }

这是网址的源代码:

<!DOCTYPE html>
<html>
    <body>
        <h1>Latest Tweet :</h1>

        <div id="Tweet"></div>

        <script>
        if (typeof (EventSource) !== "undefined") {
                var source = new EventSource( "/eirwig-spring-mvc/TwitterIreland");
                source.onmessage = function( event) {
                    document.getElementById("Tweet").innerHTML = event.data + "<br><br>";
                };
         } else { document .getElementById("Tweet").innerHTML = "Sorry, your browser does not support server-sent events...";
         }
        </script>

</body>
</html>

有什么方法可以从页面的用户端而不是源代码端收集数据?

【问题讨论】:

    标签: java android json spring parsing


    【解决方案1】:

    最简单的方法是使用代码获取消息流:

     var source = new EventSource( "/eirwig-spring-mvc/TwitterIreland");
     source.onmessage = function( event) {
         ... do the processing here ...
     };
    

    要查询 HTML,您可以尝试使用无头浏览器,例如 PhantomJS。当一些推文已经可用时,这将允许在 2 秒后解析页面内容:

    var page = require('webpage').create();
    page.open('http://google.com', function () {
        setTimeout(function() {
            console.log(page.content);
        }, 2000);
        phantom.exit();
    });
    

    【讨论】:

    • 你能帮我解释一下EventSource吗?
    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多