Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open web page with custom cookies in Python

For example, I have cookies

my_cookies = {'name': 'Albert', 'uid': '654897897564'}

and I want to open page http://website.com

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)'))
opener.open('http://website.com').read()

How I can do this with my predefined cookies ?

like image 772
Alexander Allakhverdiyev Avatar asked Nov 07 '09 08:11

Alexander Allakhverdiyev


1 Answers

You just need a few more steps:

import urllib2
import cookielib

cp = urllib2.HTTPCookieProcessor()
cj = cp.cookiejar

# see cookielib.Cookie documentation for options description
cj.set_cookie(cookielib.Cookie(0, 'a_cookie', 'a_value',
                               '80', False, 'domain', True, False, '/path',
                               True, False, None, False, None, None, None))
opener = urllib2.build_opener(urllib2.HTTPHandler(),
                              cp)
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)'))
opener.open('http://website.com').read()
like image 174
abbot Avatar answered Sep 28 '22 15:09

abbot