ich möchte mir ein Skript schreiben welches sich auf einer Webseite Einloggt und dort eine Datei runterlädt.
Das mit dem Auto-login habe ich bereits fertig, leider habe ich keine Idee wie das mit dem download gemacht wird.
Auf der Webseite befindet sich ein Formular, die Einträge werden mit POST übergeben, aber es könnte sein, dass dort erst ein javascript die Datei erstellt. Ich hoffe jemand kann mir da "unter die Tasten greifen"
Code: Alles auswählen
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cookielib
import urllib
import urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp = opener.open('http://stooq.pl') # save a cookie
theurl = 'http://stooq.pl/logred.htm' # an example url that sets a cookie, try different urls here and see the cookie collection you can make !
body={'in':'1','url':'/','login':'########','haslo':'########'}
txdata = urllib.urlencode(body) # if we were making a POST type request, we could encode a dictionary of values here - using urllib.urlencode
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} # fake a user agent, some websites (like google) don't like automated exploration
try:
req = urllib2.Request(theurl, txdata, txheaders) # create a request object
handle = opener.open(req) # and open it to return a handle on the url
HTMLSource = handle.read()
f = file('home.html', 'w')
f.write(HTMLSource)
f.close()
# http://stooq.pl/bazy/waluty.html
theurl = 'http://stooq.pl/bazy/waluty.prn'
body = {'data':'20080922','granica':'0','waluty_4':'1','beztrans':'1','prn':'1'}
txdata = urllib.urlencode(body)
req = urllib2.Request(theurl,txdata, txheaders) # create a request object
handle = opener.open(req) # and open it to return a handle on the url
HTMLSource = handle.read()
f = file('pobur.html', 'w')
f.write(HTMLSource)
f.close()
except IOError, e:
print 'We failed to open "%s".' % theurl
if hasattr(e, 'code'):
print 'We failed with error code - %s.' % e.code
elif hasattr(e, 'reason'):
print "The error object has the following 'reason' attribute :", e.reason
print "This usually means the server doesn't exist, is down, or we don't have an internet connection."
sys.exit()
else:
print 'Here are the headers of the page :'
print handle.info() # handle.read() returns the page, handle.geturl() returns the true url of the page fetched (in case urlopen has followed any redirects, which it sometimes does)
print handle.read()
print handle.geturl()