【问题标题】:Python Mechanize for form with options populated by Javascript [duplicate]带有由 Javascript 填充的选项的 Python Mechanize [重复]
【发布时间】:2012-06-13 22:37:03
【问题描述】:

我正在尝试使用 mechanize 从以下网站获取纽约地铁北部铁路的价格:http://as0.mta.info/mnr/fares/choosestation.cfm

问题在于,当您选择第一个选项时,该站点使用 javascript 来填充您的可能目的地列表。我已经在 python 中编写了等效的代码,但我似乎无法让它全部工作。到目前为止,这是我所拥有的:

import mechanize
import cookielib
from bs4 import BeautifulSoup

br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)     Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

br.open("http://as0.mta.info/mnr/fares/choosestation.cfm")

br.select_form(name="form1")
br.form.set_all_readonly(False)

origin_control = br.form.find_control("orig_stat", type="select")
origin_control_list = origin_control.items
origin_control.value = [origin_control.items[0].name]

destination_control_list = reFillList(0, origin_control_list)

destination_control = br.form.find_control("dest_stat", type="select")
destination_control.items = destination_control_list
destination_control.value = [destination_control.items[0].name]

response = br.submit()
response_text = response.read()
print response_text

我知道我没有给你 reFillList() 方法的代码,因为它很长,但假设它正确地创建了一个 mechanize.option 对象列表。 Python 没有抱怨我任何事情,但在提交时我得到了这个警报的 html:

“无法在线提供两条线路之间的票价信息。请致电 511 联系我们的客户信息中心,并要求与代表交谈以获取更多信息。”

我在这里遗漏了什么吗?感谢大家的帮助!

【问题讨论】:

    标签: python screen-scraping mechanize


    【解决方案1】:

    如果不尝试理解该函数中的疯狂逻辑,就无法真正做到这一点。我建议使用 js 解决方案或像 selenium 这样的完整浏览器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-19
      • 2015-06-15
      • 2016-04-09
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多