gpt4 book ai didi

python - Scrapy 无法在 POST 请求后检索数据

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:07 25 4
gpt4 key购买 nike

我尝试使用 scrapy 抓取一些页面,以使我的找房研究不那么乏味。我似乎遇到了需要发布请求的表单问题(我在评估员的数据库网站或租金计上没有成功,蜘蛛如下所示)。

class RentSpider(BaseSpider):
name = 'rentometer'

def start_requests(self):
request = FormRequest('http://www.rentometer.com',
formdata={'address': '179 Commonwealth Ave, Apt 1, Boston, MA', 'beds': '1'},
callback=self.after_response)
return [request]

def after_response(self, response):
with open('response_html', 'w')as f:
f.write(response.body)

我没有收到任何错误,但响应 html 似乎返回到主页,就好像没有输入任何数据一样。我确实看到蜘蛛前往 http://www.rentometer.com/results,这是表单的提交页面,但从那里我被重定向回主页。

我试图查看 cookie 以查看是否遗漏了什么,但我发现唯一感兴趣的是 session ID,我应该会自动获取它。我也偶然发现了这个问题:How to crawl a post dependent website using scrapy ,它没有解决方案,但我想知道我是否面临与该海报相同的问题,是否有任何解决方法或能够使用另一个库绕过此问题?

最佳答案

不是一个容易抓取的网站。

我用 firebug 试了一下,这是我在“网络”选项卡中看到的请求:

要求:

https://www.rentometer.com/results?

参数:

address=179%20Commonwealth%20Ave%2C%20Apt%201%2C%20Boston%2C%20MA&
authenticity_token=%2BhrOEjFfwpI6f08lgiXB5%2B%2F9bWy0y20nVnQWn%2BKGgb0%3D&
beds=1&
latitude=42.351567&
longitude=-71.07978300000002&
price=&utf8=%E2%9C%94

我又看了看页面上的表单,意识到 authenticity_token 是从页面上的另一个地方拿来的,并尝试:

from scrapy.spider import BaseSpider
from scrapy.http import FormRequest

class RentSpider(BaseSpider):
name = 'rentometer'
start_urls = [
'http://www.rentometer.com'
]

def parse(self, response):
request = FormRequest.from_response(response=response,
formxpath='//form',
formdata={'address': '179 Commonwealth Ave, Apt 1, Boston, MA',
'beds': '1',},
callback=self.after_response)
return [request]

def after_response(self, response):
with open('response_html', 'w')as f:
f.write(response.body)

这也不起作用,所以我猜这是因为缺少纬度和经度。

在 firebug 的 javacript 页面中搜索它们,我发现了以下代码部分:

$("#search_form").submit(function(t){var i,n;return e?void 0:
(t.preventDefault(),i=$("#address_field").val(),n=new google.maps.Geocoder,
n.geocode({address:i},function(t,i){var n;
return i===google.maps.GeocoderStatus.OK?(n
=t[0].geometry.location,$("#latitude").val(n.lat()),$("#longitude").val(n.lng())

我手动添加了纬度和经度值:

formdata={'address': '179 Commonwealth Ave, Apt 1, Boston, MA', 
'beds': '1',
'latitude': '42.351567',
'longitude': '-71.07978300000002'},

取得了不错的成绩。

如果您想正确生成它们,请查看 How can we execute javascript in scrapy?或者实现与 python 方法相同的逻辑作为蜘蛛的一部分

关于python - Scrapy 无法在 POST 请求后检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20819080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com