欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python中mechanize库的简单使用示例

程序员文章站 2023-01-31 10:22:47
复制代码 代码如下:#!/usr/bin/env/ python#coding=utf-8import mechanizeimport cookielib # cooki...

复制代码 代码如下:

#!/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")