代码之家  ›  专栏  ›  技术社区  ›  Pablo Santa Cruz

使用urllib2发布数据、遵循重定向和维护cookie

  •  4
  • Pablo Santa Cruz  · 技术社区  · 14 年前

    我正在使用 urllib2 在里面 蟒蛇

    成功登录后,网站会将我的请求重定向到另一个页面。有人能提供一个简单的代码示例,说明如何在Python中使用 URL库2 已登录 当我被重定向到另一个页面时。对吗?

    1 回复  |  直到 14 年前
        1
  •  6
  •   adamJLev    14 年前

    首先,机械化: http://wwwsearch.sourceforge.net/mechanize/
    您可以只使用urllib2来完成这类工作,但是您将要编写大量的样板代码,而且会出现bug。

    import mechanize
    
    br = mechanize.Browser()
    br.open('http://somesite.com/account/signin/')
    
    br.select_form('loginForm')    
    br['username'] = 'jekyll'
    br['password'] = 'bananas'
    br.submit()
    # At this point, you're logged in, redirected, and the 
    #  br object has the cookies and all that.
    
    br.geturl() # e.g. http://somesite.com/loggedin/
    

    然后可以使用浏览器对象 br