Ich habe versucht, den Prozess des Herunterladens von Bildern von bestimmten Websites zu automatisieren, und die Leute sagten mir, ich solle Python verwenden. Die Seiten der Website haben das Format http://site/... /number.html
.Beenden einer Schleife, wenn die letzte Datei ein Duplikat der aktuellen Datei ist
Piecing zusammen Dinge aus verschiedenen Quellen, landete ich mit this- bis
import os
import urllib
from urllib import urlopen
import BeautifulSoup
from BeautifulSoup import BeautifulSoup
import urllib2
import requests
import re
import hashlib
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
url = input()
usplit = re.split('/|\.', url)
title = usplit[5]
volume = None
if (usplit[6][0] == 'v'):
volume = usplit[6]
chapter = usplit[7]
pg_no = int(usplit[8])
else:
chapter = usplit[6]
pg_no = int(usplit[7])
if (volume is not None):
mpath = ".\\" + title + "\\" + volume + "\\" + chapter
if not os.path.isdir(mpath):
os.makedirs(mpath)
else:
mpath = ".\\" + title + "\\" + chapter
if not os.path.isdir(mpath):
os.makedirs(mpath)
while (1):
flg = 0
r = requests.get(url)
if (r.status_code!=200):
print "Exception: Access!"
exit()
print "Getting content from " + url
html = r.content
page = BeautifulSoup(html)
image = page.findAll('img')[0]['src']
res = urllib.urlopen (image)
prevfile = mpath + "\\" + str(pg_no-1) + ".jpg"
file = mpath + "\\" + str(pg_no) + ".jpg"
if (not (os.path.isfile(file))):
print "Writing to... " + file
output = open(file,"wb")
output.write(res.read())
output.close()
if (flg==1):
if (md5(file) == md5(prevfile)):
print "All done!"
exit()
print "Done."
else:
print str(pg_no) + ".jpg already exists, skipping..."
flg = 1
pg_no+=1
if (volume is not None):
newurl = usplit[0] + "//" + usplit[2] + "." + usplit[3] + "/" + usplit[4] + "/" + title + "/" + volume + "/" + chapter + "/" + str(pg_no) + "." + usplit[9]
else:
newurl = usplit[0] + "//" + usplit[2] + "." + usplit[3] + "/" + usplit[4] + "/" + title + "/" + chapter + "/" + str(pg_no) + "." + usplit[8]
url = newurl
Das Problem ist, nachdem ich das letzte Bild erreicht, leitet die Webseite mich auf die letzte gültige Seite. Das heißt, wenn 46.html
die letzte Seite ist, wird die Anforderung für 47.html
dorthin umgeleitet, und r.status_code
bleibt gleich. Um dies zu umgehen, habe ich versucht, die zuletzt heruntergeladene Datei und die aktuelle Datei zu vergleichen und das Programm zu beenden. Dies scheint jedoch nicht zu funktionieren. Ich bin neu und unsicher, wie man die Dateien vergleicht, und MD5-Funktion war etwas, das ich fand here. Ich habe versucht mit filecmp
auch, aber es scheint auch nicht zu funktionieren.
Irgendwelche Vorschläge? Gibt es bezüglich des Codes auch etwas, das mehr Python-y gemacht werden könnte?