Scrapy POST请求无效 - 400 Bad Request

时间:2017-02-15 12:05:33

标签: python scrapy python-requests http-status-code-400

我正在从python的Item -Title -Date -Specifications [Array] -- [0] Name: "Watt" -- [0] Value: 5 -- [1] Name: "Weight" -- [1] Value: 100 库迁移到requests,我在制作简单的POST请求时遇到问题。我正在设置标题和有效负载:

scrapy

然后提出这样的请求:

headers = {
    'Accept':'*/*',
    'Accept-Encoding':'gzip, deflate, br',
    'accept-language':'en_US',
    'Connection':'keep-alive',
    'Content-Length':'151',
    'content-type':'application/json',
    'Cookie':cookie,
    'Host':host,
    'Origin':origin,
    'Referer':referer,
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
    'x-csrf-token':token
}

payload = {"targetLocation":{"latitude":lat,"longitude":lng}}

这继续给我400状态。如果我使用与def start_requests(self): u = self.url yield scrapy.Request(u, method='POST', callback=self.parse_httpbin, errback=self.errback_httpbin, body=json.dumps(self.payload), headers=self.headers) 库完全相同的标头和有效负载来发出请求,它会给我200状态并返回一个json,如预期的那样。

requests

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的请求中的几个标头不建议使用通用HTTP库。大多数图书馆都会自己生成这些:

  • 主机
  • 的Content-Length

具体来说,HTTP RFC非常明确地指出,每当Content-Length标头被多次发送(S​​crapy可能正在执行)时,响应必须为400.请求,可能没有设置它自己的Content-Length标题,而是按照你的标准。