Scrapy ajax POST请求不工作,但在Postman中工作

Scrapy ajax POST请求不工作,但在Postman中工作,ajax,post,scrapy,postman,Ajax,Post,Scrapy,Postman,我正在实现一个scrapy spider来抓取包含房地产报价的网站。该网站包含房地产代理的电话号码,可以通过ajax post请求检索该号码。scrapy生成的请求从服务器返回错误,而从Postman发送的相同请求返回所需的数据 以下是网站URL: 我使用chrome的开发工具中的网络选项卡记录了请求。ajax请求的url是:发送请求所需的数据是页面源中包含的CSRFtoken,它会定期更改。在Postman中,仅将CSRFtoken作为表单数据给出预期答案 这是我在scrapy中构造请求的方式

我正在实现一个scrapy spider来抓取包含房地产报价的网站。该网站包含房地产代理的电话号码,可以通过ajax post请求检索该号码。scrapy生成的请求从服务器返回错误,而从Postman发送的相同请求返回所需的数据

以下是网站URL:

我使用chrome的开发工具中的网络选项卡记录了请求。ajax请求的url是:发送请求所需的数据是页面源中包含的CSRFtoken,它会定期更改。在Postman中,仅将CSRFtoken作为表单数据给出预期答案

这是我在scrapy中构造请求的方式:

    token_input = response.xpath('//script[contains(./text(), "csrf")]/text()').extract_first()
    csrf_token = token_input[23:-4]

    offerID_input = response.xpath('//link[@rel="canonical"]/@href').extract_first()
    offerID = (offerID_input[:-5])[-7:]

    form_data = {'CSRFToken' : csrf_token}

    request_to_send = scrapy.Request(url='https://www.otodom.pl/ajax/misc/contact/phone/3ezHA/', headers = {"Content-Type" : "application/x-www-form-urlencoded"}, method="POST", body=urllib.urlencode(form_data), callback = self.get_phone)

    yield request_to_send

不幸的是,我得到了一个错误,虽然一切都应该是好的。有人知道可能是什么问题吗?可能与编码有关吗?该站点使用utf-8。

您可以在页面源中找到令牌:

<script type="text/javascript">
var csrfToken = '0ec80a520930fb2006e4a3e5a4beb9f7e0d6f0de264d15f9c87b572a9b33df0a';
</script>
要获得全部信息,您可以使用scrapy的
FormRequest
,它可以为您发出正确的post请求:

def parse(self, response):
    token = re.findall("csrfToken = '(.+?)'", response.body)[0]
    yield FormRequest('https://www.otodom.pl/ajax/misc/contact/phone/3ezHA/',
                      formdata={'CSRFToken': token},
                      callback=self.parse_phone)

def parse_phone(self, response):
    print(response.body)
    #'{"value":"515 174 616"}'
您可以通过插入
inspect\u response
调用并查看
request
对象来调试scrapy请求:

def parse_phone(self, response):
    from scrapy.shell import inspect_response
    inspect_response(response, self)
    # shell opens up here and spider is put on pause
    # now check `request.body` and `request.headers`, match those to what you see in your browser 

我在获取令牌方面没有问题,我甚至发布了获取令牌的代码。问题在于请求-它有所有需要的数据,并且返回了一个错误。@jkwi哦,对不起,我误解了你的问题。请参阅我的编辑以获取完整答案。感谢您的更新,它的工作非常有魅力。干杯
def parse_phone(self, response):
    from scrapy.shell import inspect_response
    inspect_response(response, self)
    # shell opens up here and spider is put on pause
    # now check `request.body` and `request.headers`, match those to what you see in your browser