2014-10-30 47 views
-1

我想根据Chrome检查器(网络选项卡)中显示的XHR数据完全创建发布请求。我们的目标是重新创建一个AJAX请求去一个动态显示的页面4.使用浏览器的XHR日志重新创建AJAX请求

我编程它是这样:

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 \”:\“NombreCompañia\”,\“tip# .....等等

有没有我应该知道的编码问题?
此外,我必须通过所有标题?

非常感谢!

+0

@ S精益不幸的是,你需要更具体。没有任何信息可以理解您的问题 – 2014-10-31 12:06:31

+0

@Mohsin我还可以包含哪些内容?我包括目标,代码,网址,结果(404页未找到)以及假设的原因......请让我知道,我会很乐意添加它。 – 2014-10-31 15:09:30

+0

@ S Lean您能否介绍一下您正在关注的导航步骤 - 哪个网址(首先出现) - 然后是您发布的内容?哪个领域是那个。要说我关于我目前在这个页面,然后不知道你想要做的下一步 - http://www.metrocuadrado.com/web/buscarFiltros/bogota-apartamento-venta – 2014-10-31 16:11:18

回答

0

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

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

2)有效载荷是JSON,所以我们将不得不使用json.dumps发送POST请求。 最后发送指示后请求Content-Typeapplication/json

我们可以做这样的事情,

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

让我知道,如果你面对任何问题:-)

+0

这个解决方案对我来说几乎完美。我只需要改变一行,添加'html5':soup = bs(r.content,'html5') – 2014-10-31 21:50:47

+0

太棒了! :-) 很高兴我能帮上忙 – 2014-10-31 22:19:25