How to get cookies from urllib.request?

How to get cookie with urllib.request?

import urllib.request
import urllib.parse

data = urllib.parse.urlencode({
    'user': 'user',
    'pass': 'pass'
})
data = data.encode('utf-8')

request = urllib.request.urlopen('http://example.com', data)
print(request.info())

request.info() returns cookies, but not in a very convenient way.

+4
source share
1 answer

I think using requests is a much better choice these days. Try this sample code that shows the Google settings cookie when you visit:

import requests

url = "http://www.google.com"
r = requests.get(url,timeout=5)
if r.status_code == 200:
    for cookie in r.cookies:
        print(cookie)            # Use "print cookie" if you use Python 2.

gives:

Cookie NID=67=n0l3ME1Jl3-wwlH7oE5pvxJ_CfU12hT5Kh65wh21bvE3hrKFAo1sJVj_UcuLCr76Ubi3yxENROaYNEitdgW4IttL43YZGlf8xAPl1IbzoLG31KP5U2tiP2y4DzVOJ2fA for .google.se/

Cookie PREF=ID=ce66d1288fc0d977:FF=0:TM=1407525509:LM=1407525509:S=LxQv7q8fju-iHJPZ for .google.se/
+3
source

All Articles