如何使用Python请求获取请求标头而不是响应标头

时间:2015-12-15 14:44:16

标签: python xmlhttprequest python-requests

如何使用Python Requests模块获取XHR请求的请求标头?使用以下代码似乎返回响应标头:

app.controller('ForecastController', ['forecastService', function(forecastService) {

    /*  $scope.forecastData = [ {"id":1,"value_kwh":1000.0,"forecast_date":"2015-11-27T00:00:00"},{"id":2,"value_kwh":1000.0,"forecast_date":"2015-11-28T00:00:00"},{"id":4,"value_kwh":1000.0,"forecast_date":"2015-11-29T00:00:00"}]; */

    var self = this
    self.forecastData = [];
    self.newForecast = {};

    var getData = function(){
        return forecastService.get().then(
            function(response){
                self.forecastData  = response.data;
            }, function(errResponse){
                console.error('Error while fetching data: ');
                console.error(errResponse);
            });
    };

    getData();

    self.create = function(){    
        forecastService.create(self.newForecast)
            .then(getData)
            .then(function(response){
                self.newForecast = {};
            }); 
    };  
}]);

这将返回一个如下所示的对象:

import requests

r = requests.get('http://www.whoscored.com/tournamentsfeed/12496/Fixtures/?d=2015W50&isAggregate=false')
headers = r.headers
print headers

但是,当我查看Chrome开发者工具时,请求标题如下所示:

{'content-length': '624', 'content-encoding': 'gzip', 'expires': '-1', 'vary': 'Accept-Encoding', 'server': 'Microsoft-IIS/8.0', 'pragma': 'no-cache', 'cache-control': 'no-cache', 'date': 'Tue, 15 Dec 2015 14:41:34 GMT', 'x-powered-by': 'ASP.NET', 'content-type': 'text/html; charset=utf-8'}

有人可以帮忙吗?

由于

1 个答案:

答案 0 :(得分:1)

你需要检查像这样的请求标题

{'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.7.0 CPython/2.7.10 Darwin/15.0.0'}

这会给你类似的东西

requests

由于显而易见的原因,它与您在Chrome开发人员工具中看到的不一样,因为浏览器会添加自己的标头GET /tournamentsfeed/12496/Fixtures/?d=2015W50&isAggregate=false HTTP/1.1 Host: www.whoscored.com Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6 Cookie: _ga=GA1.2.788154924.1450195026; _gat_as25n45=1 模块没有。

self.tableViewController.layoutIfNeeded()

要获取这些标头,您需要运行一些js代码来拉取标题。