urllib2在windows和* nix平台之间执行不同的操作?

时间:2011-01-02 05:09:47

标签: python urllib2

这个简单的脚本执行自动登录操作。它可以在我的Linux机器(Python 2.7)和笔记本电脑(Mac OSX Python2.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 :(得分:2)

这不是Nix与Windows的问题......你的代码在两个平台上都失败了:)

这条线错了:

opener=urllib2.build_opener(request,cj)

试试这个:

opener = urllib2.build_opener(cj)

你正在调用build_opener()错误。请参阅python docs

另外,你有一个额外的httplib导入,你不需要

然而, REAL 答案是:对这样的事情使用mechanize。它比使用urllib2(自动处理cookie)容易得多。

答案 1 :(得分:0)

为什么要混合urllib和urllib2

postdata=urllib.urlencode({'username':name,'password':pwd})
request=urllib2.Request(url_hi,postdata)