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

标签 python screen-scraping web-scraping mechanize mechanize-python

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

    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。你会很高兴你做到了。

关于Python 和 Mechanize : How to scrape through pages in a row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13195575/

相关文章:

python - ESPN.com Python 网页抓取问题

javascript - 在尝试抓取 React 网站时获取 index.html 内容

python - ValueError : s must be a scalar, 或与 x 和 y 大小相同

python - 从 C++ 运行 python 脚本时内存泄漏

python - 在 DJANGO CRUD 数据库应用程序中创建父/主条目然后将关联数据字段添加到父/主条目的最佳方法是什么?

c# - 在 C# 中下载整个网站

javascript - 我怎样才能使用 puppeteer 作为 cachewarmer?

python - 在 matplotlib 中创建表

python - Scrapy Max重定向问题

python - Scrapy - 在请求中更改用户代理的正确方法