【问题标题】:Using the browser's XHR log to recreate an AJAX request使用浏览器的 XHR 日志重新创建 AJAX 请求
【发布时间】:2014-11-01 01:23:52
【问题描述】:

我想创建一个完全基于 Chrome 检查器(网络选项卡)中显示的 XHR 数据的发布请求。目标是重新创建 AJAX 请求以转到动态显示的页面 4。

我是这样编程的:

from requests import Session
session = requests.Session()

session.head('http://www.metrocuadrado.com/web/buscarFiltros/bogota-apartamento-venta')

payload = {...}   #copied and pasted literally from the (previously inspected) source code of the XHR request
headersxhr = {...}   #dictionary of all the headers found in the (previously inspected) source code of the XHR

response = session.post(
    url = 'http://www.metrocuadrado.com/web/busqueda/pagina-4',
    data = payload,    
    headers = headersxhr
    )

print response.text

不幸的是,这给了我一个 404 错误。粘贴的有效载荷很长,有很多嵌套的字典。开头是这样的:

{"token":"","cantidadResultadosPagina":"16","filtrosJson":"\t\t\n\t\t{\"mnombreinmobiliaria\": {\"nombre\" :\"mnombreinmobiliaria\",\"valor\":[\"\"],\"valor2\":null,\"descripcion\":\"Nombre Compañia\",\"tip #. ....等等

是否存在我应该注意的编码问题?
另外,我必须通过所有标题吗?

非常感谢!!

【问题讨论】:

  • @S Lean 不幸的是,您需要更具体。甚至没有任何信息可以了解您的问题
  • @Mohsin 我还能包括什么?我包括了目标、代码、URL、结果(404 页面未找到)和假设原因......请告诉我,我会很乐意添加。
  • @S Lean 您能否解释一下您遵循的导航步骤 - 哪个 url(先行) - 那么您是在发帖吗?那是哪个领域。说一下我,我目前在这个页面,然后不知道你接下来想做什么 -- metrocuadrado.com/web/buscarFiltros/bogota-apartamento-venta
  • 在广告列表的底部,我点击转到第 4 页(第 4 页)。这是一个 ID="paginador_pagina_4" 的元素。
  • @S Leon 知道了!现在发布答案:-)

标签: ajax xmlhttprequest python-requests


【解决方案1】:

1) filtrosJson 是随机生成的代码。在第一页的源代码中可以找到。

我们首先需要使用您喜欢的任何方法来获取它,现在我使用的是bs4

2) 负载是 json 格式,所以我们必须使用 json.dumps 来发送 post 请求。 最后发送指示Content-Typeapplication/json 的post 请求

我们可以这样做,

import requests, json
from bs4 import BeautifulSoup as bs

s=requests.Session()
headers={"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"}
s.headers.update(headers)

r=s.get("http://www.metrocuadrado.com/web/buscarFiltros/bogota-apartamento-venta")

soup=bs(r.content)
filtrosJson=soup.find(id="filtrosJson").text
data={"cantidadResultadosPagina": "16","filtroOrdenamiento": "-1","filtrosJson":filtrosJson,"token": ""}


r=s.post("http://www.metrocuadrado.com/web/busqueda/pagina-4",data=json.dumps(data),headers={"X-Requested-With":"XMLHttpRequest","Content-Type":"application/json"})

print r.json()

这适用于我在 Python2.7、Ubuntu 14.04 上

如果您遇到任何问题,请告诉我 :-)

【讨论】:

  • 这个解决方案对我来说几乎是完美的。我只需要更改一行,添加 'html5' :soup=bs(r.content, 'html5')
  • 太棒了! :-) 很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 2015-08-26
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多