I’m trying to do some scraping of a site that requires authentication (not http auth). The script I’m using is based on this eventlet example. Basically,
urls = ["https://mysecuresite.com/data.aspx?itemid=blah1",
"https://mysecuresite.com/data.aspx?itemid=blah2",
"https://mysecuresite.com/data.aspx?itemid=blah3"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
print "opening", url
body = urllib2.urlopen(url).read()
print "done with", url
return url, body
pool = eventlet.GreenPool(10)
for url, body in pool.imap(fetch, urls):
print "got body from", url, "of length", len(body)
Establishing the session is not simple at all; I have to load the login page, extract some variables from the login form, then send a POST request with the auth details and those variables. After the session is good, the rest of the requests are simple GET requests.
Using the above code as a reference point, how would I create a session that the rest of the pool would use? (I need the subsequent requests to be made in parallel)
I’m not an expert on this by any means, but it looks like the standard way to maintain session state with urllib2 is to create a custom opener instance for each session. That looks like this:
Then you use that opener to do whatever authentication you have to, and all the session state will remain within the opener object itself. Then you can pass the opener object as an argument for the parallel requests.
Here is an example script that logs in to secondlife.com for multiple users in parallel, and makes multiple page requests for each user, also in parallel. The login procedure for this particular site is tricky because it involves capturing a CSRF token from the first request before being able to log in with the second. For that reason, the login method is quite messy. The principle should be the same, though, for whatever site you’re interested in.