Skip to main content
 首页 » 编程设计

Python 和 Mechanize : How to scrape through pages in a row

2025年05月04日22qq78292959

我的问题如下: 我正在尝试编写一个贯穿航空公司票务网站订购流程的抓取工具。所以我想根据之前页面的结果抓取几个页面(我希望你明白我的意思)。我现在到目前为止:

    import mechanize, urllib, urllib2 
 
    url = 'any url' 
    br = mechanize.Browser() 
    br.set_handle_robots(False) 
    br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 5.2; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11')] 
    br.open(url) 
    response = br.response().read() 
 
    br.select_form(nr=1) 
    br.form.set_all_readonly(False) 
 
    ## now I am reading out the variables of form(nr=1) 
 
    for control in br.form.controls: 
           if not control.name: 
               print " - (type) =", (control.type) 
               continue   
           print " - (name, type, value) =", (control.name, control.type, br[control.name]) 
 
    ## now I am modifying the variables 
    br['fromdate'] = '2012/11/03' 
    br['todate'] = '2012/11/07' 
 
    ## now I am submitting the form and saving the output in the variable bookingsite 
    response = br.submit() 
    bookingsite = response.read() 

这是我的问题:如何使用变量 bookingsite,它又包含一个我想修改和提交的表单,就像普通 URL 一样?只需通过设置

    br.open(bookingsite) 

???或者是否有另一种修改和提交输出的方法(然后再次提交输出并接收新的输出页面)?

请您参考如下方法:

在您的初始响应 response = br.submit() 从响应对象中选择表单:

response.select_form() 

更改表单中字段的值后,提交表单:

response.submit() 

附言如果您要自动化预订网站,他们很可能有大量的 Javascript。 Mechanize 不处理 Javascript。我建议改用 Requests。你会很高兴你做到了。