Problems saving cookies when making HTTP requests using Python
Question: I‘m trying to make a web-spider using python but I've got some problems when I
tried to login the web site Pixiv.My code is as below:

    
    
    import sys
    import urllib
    import urllib2
    import cookielib
    
    url="https://www.secure.pixiv.net/login.php"
    
    cookiename='123.txt'
    cookie = cookielib.MozillaCookieJar(cookiename)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    cookie.save()
    
    values={'model':'login',
            'return_to':'/',
            'pixiv_id':'username',
            'pass':'password',
            'skip':'1'}
    
    headers = { 'User-Agent' : 'User-Agent' }
    data=urllib.urlencode(values)
    req=urllib2.Request(url,data)
    response=urllib2.urlopen(req)
    the_page=response.read()
    cookie.save()
    

To make sure it works, I used the cookielib to save the cookie as a txt file.I
ran the code and got a "cookie.txt",but when I open the file I found that it
was rmpty,in another word,my code didn't work. I don't know what's wrong with
it.


Answer: The problem is you're not using the `opener` that you created with the
cookiejar attached to it in order to make the request. `urllib2.urlopen` has
no way of knowing that you want to use that opener to start the request.

You can either use the opener's
[`open`](https://docs.python.org/2/library/urllib2.html#urllib2.OpenerDirector.open)
method directly or, if you want to use this by default for the rest of your
application, you can install it as the default opener for all requests made
with `urllib2` using
[`urllib2.install_opener`](https://docs.python.org/2/library/urllib2.html#urllib2.install_opener).
So give that a try and see if it does the trick.

