HTTPS log in with urllib2

2024/10/18 14:52:17

I currently have a little script that downloads a webpage and extracts some data I'm interested in. Nothing fancy.

Currently I'm downloading the page like so:

import commands
command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx'
status, text = commands.getstatusoutput(command)

Although this works perfectly, I thought it'd make sense to remove the dependency on wget. I thought it should be trivial to convert the above to urllib2, but thus far I've had zero success. The Internet is full urllib2 examples, but I haven't found anything that matches my need for simple username and password HTTP authentication with a HTTPS server.

Answer

this says, it should be straight forward

[as] long as your local Python has SSL support.

If you use just HTTP Basic Authentication, you must set different handler, as described here.

Quoting the example there:

import urllib2theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'
username = 'johnny'
password = 'XXXXXX'
# a great passwordpassman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for  urls
# for which `theurl` is a super-urlauthhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandleropener = urllib2.build_opener(authhandler)urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.pagehandle = urllib2.urlopen(theurl)
# authentication is now handled automatically for us

If you do Digest, you'll have to set some additional headers, but they are the same regardless of SSL usage. Google for python+urllib2+http+digest.

Cheers,

https://en.xdnf.cn/q/72947.html

Related Q&A

Filter values inside Python generator expressions

I have a dictionary dct for which I want each of its values to be summed provided their corresponding keys exist in a specified list lst.The code I am using so far is:sum(dct[k] for k in lst)In the abo…

Python and tfidf algorithm, make it faster?

I am implementing the tf-idf algorithm in a web application using Python, however it runs extremely slow. What I basically do is:1) Create 2 dictionaries:First dictionary: key (document id), value (lis…

How to use Python to find all isbn in a text file?

I have a text file text_isbn with loads of ISBN in it. I want to write a script to parse it and write it to a new text file with each ISBN number in a new line.Thus far I could write the regular expres…

AWS Batch Job Execution Results in Step Function

Im newbie to AWS Step Functions and AWS Batch. Im trying to integrate AWS Batch Job with Step Function. AWS Batch Job executes simple python scripts which output string value (High level simplified req…

Simplify Django test set up with mock objects

Often when Im writing tests for my Django project, I have to write a lot more code to set up database records than I do to actually test the object under test. Currently, I try to use test fixtures to …

How to use tf.data.Dataset.padded_batch with a nested shape?

I am building a dataset with two tensors of shape [batch,width,heigh,3] and [batch,class] for each element. For simplicity lets say class = 5.What shape do you feed to dataset.padded_batch(1000,shape)…

Python, thread and gobject

I am writing a program by a framework using pygtk. The main program doing the following things:Create a watchdog thread to monitor some resource Create a client to receive data from socket call gobjec…

How to type annotate overrided methods in a subclass?

Say I already have a method with type annotations:class Shape:def area(self) -> float:raise NotImplementedErrorWhich I will then subclass multiple times:class Circle:def area(self) -> float:retur…

Import Error: No module named pytz after using easy_install

Today is my first day at Python and have been going through problems. One that I was working on was, "Write a short program which extracts the current date and time from the operating system and p…

Python catch exception pandas.errors.ParserError: Error tokenizing data. C error

I am facing problem with my malfunction csv input file whole reading and which i can deal with by adding "error_bad_lines=False" in my read_csv func to remove those.But i need to report these…