1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
import urllib
import urllib2
import cookielib
COOKIE_FILE = "cookies.lwp"
top_url = "localhost:8080"
username = "user"
password = "pass"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { "User-Agent" : user_agent }
opener = None
# Basic authentification (Base64(user:pwd))
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add username and password. If we new the domain, could use it instead of None.
password_mgr.add_password(None, top_url, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# cookie section
cj = cookielib.LWPCookieJar()
if cj is not None:
# we successfully imported
# one of the two cookie handling modules
if os.path.isfile(COOKIE_FILE):
# if we have a cookie file already saved
# then load the cookies into the Cookie Jar
cj.load(COOKIE_FILE)
# Now we need to get our Cookie Jar
# installed in the opener;
# for fetching URLs
if cookielib is not None:
# if we use cookielib
# then we get the HTTPCookieProcessor
# and install the opener in urllib2
opener = urllib2.build_opener(auth_handler, urllib2.HTTPCookieProcessor(cj))
else:
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener) |
Partager