简体   繁体   中英

TypeError: expected BaseHandler instance, got <type 'str'>

import urllib2, re, urllib

def login():
    host = "http://localhost/cms/"
    user = 'admin'
    passw = 'admin'
    error = "Login to CMS Made Simple"
    form = [
        ('username', user),
        ('password', word)]   
    target = host + "/admin/login.php"
    login_form_data = urllib.urlencode(form)
    opener = urllib2.build_opener(target)
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]
    source = opener.open(target, login_form_data).read()
    if re.search(error, source) == None : 
        print 'FOund =>>>' + target + 'Username : ' + user + 'Password :  ' + word
    else: 
        print 'Not Found=>> ' + target + '  Username : ' + user + 'Password :  ' + word

login()

I'm getting this:

    opener = urllib2.build_opener(host)
  File "D:\Python27\lib\urllib2.py", line 486, in build_opener
    opener.add_handler(h)
  File "D:\Python27\lib\urllib2.py", line 322, in add_handler
    type(handler))
TypeError: expected BaseHandler instance, got <type 'str'>

I think the problem is here: opener = urllib2.build_opener(target)

But how to solve it? I tried a lot.

Regarding to docs for urllib2.build_opener :

handlers can be either instances of BaseHandler, or subclasses of BaseHandler (in which case it must be possible to call the constructor without any parameters).

You try to pass str instead:

target=host+"/admin/login.php"
... 
opener = urllib2.build_opener(target)

Try requests library with simplified API to fetch URLs.

If you just remove the line, it will work; build_opener does not need arguments unless you want it to do something specific. In this instance, you may want to add a CookieProcessor if the server expects to use cookies to keep you logged in.

cjar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cjar)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM