urllib2在Windows和*nix平台表现不同?
这个简单的脚本可以自动登录。它可以在我的Linux电脑(使用Python 2.7)和笔记本电脑(使用Mac OSX的Python 2.5)上运行,但在Windows XP上(无论是Python 2.6还是2.7)我遇到了问题。
Traceback (most recent call last):
File "E:\workspace\python\login_baidu.py", line 22, in <module>
h=auto_login_hi(url,name,password)
File "E:\workspace\python\login_baidu.py", line 12, in auto_login_hi
opener=urllib2.build_opener(request,cj)
File "C:\Python27\lib\urllib2.py", line 477, in build_opener
opener.add_handler(h)
File "C:\Python27\lib\urllib2.py", line 311, in add_handler
type(handler))
TypeError: expected BaseHandler instance, got <type 'instance'>
我的脚本:
import urllib,urllib2,httplib,cookielib
def auto_login_hi(url,name,pwd):
url_hi="http://passport.baidu.com/?login"
cookie=cookielib.CookieJar()
cj=urllib2.HTTPCookieProcessor(cookie)
postdata=urllib.urlencode({'username':name,'password':pwd})
request=urllib2.Request(url_hi,postdata)
opener=urllib2.build_opener(request,cj)
f=opener.open(request)
print f
hi_html=opener.open(url)
return hi_html
if __name__=='__main__':
name='myusername'
password='mypasswd'
url='http://hi.baidu.com/leemzoon'
h=auto_login_hi(url,name,password)
print h.read()
2 个回答
0
你为什么把urlib和urlib2混在一起使用呢?
postdata=urllib.urlencode({'username':name,'password':pwd})
request=urllib2.Request(url_hi,postdata)