2

我正在尝试使用 angularjs / javascript 抓取网站。

我知道 angularjs 提供了一个$http对象,我可以用它发出 get 请求。我以前用这个来获取json,我可以用同一个对象来获取XML(HTML)吗?(我相信响应将使用 gzip 进行编码)。

谢谢!

4

2 回答 2

2

获取 xml 文件$httpProvider不会以 DOM 的形式将响应数据传递到您的回调中。

使用以下示例作为模式,并使用DOMParser旧 IE 客户端中的或适当的 ActiveX 对象转换返回的文本。

exampleModule = angular.module('exampleModule', []);
exampleController = exampleModule.controller('exampleController', ['$scope', '$http', function ($scope, $http) {
    $http.get("example.xml").then(function (response) {
        var dom;
        if (typeof DOMParser != "undefined") {
            var parser = new DOMParser();
            dom = parser.parseFromString(response.data, "text/xml");
        }
        else {
            var doc = new ActiveXObject("Microsoft.XMLDOM");
            doc.async = false;
            dom = doc.loadXML(response.data);
        }
        // Now response is a DOMDocument with childNodes etc.
        return dom;
    });
}]);

于 2015-03-30T19:34:34.517 回答
-1

您应该能够$http用于获取 JSON 以外的响应数据。该$http文档解释说,默认响应转换之一是If JSON response is detected, deserialize it using a JSON parser. 但是,如果您请求其他内容(例如 HTML 模板)response.data,则应该具有该 HTML 的字符串值。事实上,Angular$http用于下拉 HTML 以用于ngInclude等。

gzip(或在这种情况下解压缩)应在响应到达$http.

于 2013-10-28T19:21:51.870 回答