python中mechanize库的简单使用示例
#!/usr/bin/env/ python
#coding=utf-8
import mechanize
import cookielib
# cookie jar
cj = cookielib.lwpcookiejar()
# browser
br = mechanize.browser()
br.set_cookiejar(cj)
# browser options
br.set_handle_equiv(true)
br.set_handle_gzip(true)
br.set_handle_redirect(true)
br.set_handle_referer(true)
br.set_handle_robots(false)
# follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.httprefreshprocessor(), max_time=1)
# want debugging messages?
#br.set_debug_http(true)
#br.set_debug_redirects(true)
#br.set_debug_responses(true)
# user-agent (http header)
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/4.0.0')]
# http access and get response pack
br.open("http://hi.baidu.com/alalmn")
print br.response().read().decode("utf-8")