download.html
urls.py |
urlpatterns = [ path(‘download’, views.download, name=’download’),] |
download.html |
{% extends ‘app/base.html’ %}{% block content %} <form method=”POST” action=”{% url ‘app:download’ %}”> {% csrf_token %} {{ form.as_p }} <button type=”submit”>DOWNLOAD</button> </form>{% endblock %} |
models.py |
class Download(models.Model): website = models.CharField(max_length=200) directory = models.TextField(blank=True) def __str__(self): return self.website |
admin.py |
from .models import Downloadclass DownloadAdmin(admin.ModelAdmin): list_display = (‘id’,’website’) list_display_link = (‘id’,’website’)admin.site.register(Download,DownloadAdmin) |
forms.py |
class Download(ModelForm): class Meta: model = Download fields = [‘website’,’directory’] |
複数のWebサイトから大量の画像をDLする場合、
downloadフォルダにフォルダを新規作成し、その中に画像を一括DLした方が便利
open(‘./’ + imglist.split(‘/’)[-1], ‘wb’)とした場合、manage.pyと同階層に画像が保存される
views.py |
def download(request): if request.method == ‘POST’: form = DownloadForm(request.POST) if form.is_valid(): form.save() url = request.POST[‘website’] r = requests.get(url) bs = BeautifulSoup(r.content, ‘html.parser’) imgs = bs.find_all(‘img’) imglists = [] for img in imgs: img = img.get(‘src’) if img.endswith(‘jpg’) or img.endswith(‘png’): imglists.append(img) os.makedirs(r’C:/Users/wiki1/Downloads/’ + url.split(‘//’)[-1]) for imglist in imglists: with open(r’C:/Users/wiki1/Downloads/’ + url.split(‘//’)[-1] + ‘/’ + imglist.split(‘/’)[-1], ‘wb’) as f: f.write(requests.get(imglist).content) return redirect(‘app:index’) else: form = DownloadForm() return render(request, ‘app/download.html’, {‘form’:form}) |
※imgフォルダしかなかったとする
os.mkdir()だとその一つ下の階層のフォルダまでしか作れない
os.makedirs()なら2つ3つ下のフォルダまで一気に作れる
ただし、
url = request.POST[‘website’]
os.makedirs(r’C:/Users/wiki1/Downloads/’ + url)
とした場合、次のブラウザエラーが発生する。
[WinError 123] ファイル名、ディレクトリ名、またはボリューム ラベルの構文が間違っています。
変数urlはhttps://9ml.orgなので9ml.orgだけを抜き出すために、
os.makedirs(r’C:/Users/wiki1/Downloads/’ + url.split(‘//’)[-1])
とすればOK
BACK