Mechanize 提交结果页面不正确

问题描述 投票:0回答:2

我试图抓取 booking.com 作为学习 Mechanize 的练习,但我无法解决一个问题。我正在尝试使用以下代码通过 Mechanize 获取酒店价格:

hotel_name = "Hilton New York"
date = Date.today
day_after_date = date + 1
agent = Mechanize.new

homepage = agent.get("http://www.booking.com")
# Fill out the main form on the booking.com homepage
main_form = homepage.form_with(name: 'frm')
main_form.ss = hotel_name
main_form.checkin_monthday = date.day.to_s
main_form.checkin_year_month = "#{date.year}-#{date.month}"
main_form.checkout_monthday = day_after_date.day.to_s
main_form.checkout_year_month = "#{day_after_date.year}-#{day_after_date.month}"
main_form[''] = 1 # 1 adult, 0 children

homepage.save('1-homepage.html') # For debugging purposes

# Choose the hotel from the list that comes up
hotel_selection_page = agent.submit main_form
hotel_link = hotel_selection_page.links.select { |link| link.text =~ /#{hotel_name}/i }.first
hotel_page = hotel_link.click

# For debugging purposes
hotel_selection_page.save('2-hotels-list.html')
hotel_page.save('3-hotel-page.html')

如果您通过网络浏览器关注页面,您将看到在主页上提交表格并在下一页选择酒店后,您会看到所选日期的房价。

但是通过 Mechanize,在

3-hotel-page.html
页面上,您看不到价格。

我已经解决这个问题有一段时间了,但我似乎无法解决它。我认为问题在于 booking.com 使用的 JavaScript,但即使在我的网络浏览器上关闭 JavaScript 后,我仍然能够获得正确的行为。

对此有什么想法吗?

编辑:我刚刚意识到,当通过网络浏览器发送表单时,在您选择酒店的第二页上,酒店链接有一个

sid
参数(例如,
sid=ba232d9d340c66ae73f1ded22b80a0da
),但是当我发送时通过 Mechanize 的形式,我没有得到
sid
参数。可能是什么原因?

ruby web-scraping mechanize
2个回答
0
投票

添加以下行来更改用户代理最终成功:

agent.user_agent_alias = 'Mac Safari'

0
投票

解决这些问题的最佳方法是通过 Charles 或 Fiddler 等调试代理代理 Mechanize 请求和浏览器请求,并并排比较它们。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.