LoginSignup
38
70

More than 3 years have passed since last update.

Pythonスクレイピングによる画像ダウンロード

Last updated at Posted at 2021-02-06

0. はじめに

ホームページの模写をするのに画像をすべてダウンロードするのが面倒だ、と思ったことはないだろうか。urlと保存先のディレクトリ名を入力しただけでそのページに使われている画像をすべてダウンロードする機能を作成したから以下にまとめる。

1. 必要なモジュール

必要なモジュールは以下の通りだ。requestsbs4はあらかじめpip等でインストールする必要がある。又、importする必要はないがhtml5libも使用する。

import os, time, requests, urllib
from bs4 import BeautifulSoup
powershell
python -m pip install requests
python -m pip install bs4
python -m pip install html5lib

2. urlとDL先ディレクトリ名の指定

urlとディレクトリ名はinputで指定する。又、savedirには任意のパスを渡すことで好きな場所にディレクトリを作成することができる。

page_url = input("urlを入力してください")
img = input("フォルダ名を入力してください")
save_dir = "./{}".format(img)

3. 画像の抽出

HTMLを勉強している人は知っていると思うが、画像は<img>というタグでページ内に埋め込まれており、srcでパスが指定されている。そこで、BeautifulSoupを用いて画像タグを抽出する。

def get_img_urls(html):
    soup = BeautifulSoup(html, "html5lib")
    res = []
    for img in soup.find_all("img"):     #soup.find_all("img")でimgタグを抽出
        src = img["src"]     #画像のパスを抽出
        url = urllib.parse.urljoin(page_url, src)     #ページのurlと画像のパスで絶対urlを作成する
        print("img.src=", url)
        res.append(url)
    return res

4. 画像のダウンロード

指定したディレクトリが存在しなければディレクトリを作成する。その後作成した絶対urlから画像をダウンロードする。又、1枚ダウンロードするごとにsleepで1秒処理を休止する。これはサーバーに高負荷を掛けないようにする処理である。

def downloads(urls):
    if not os.path.exists(save_dir):
        os.mkdir(save_dir)
    for url in urls:
        fname = os.path.basename(url)
        save_picture = save_dir + "/" + fname     #画像ファイルのパスを作成
        r = requests.get(url)
        with open(save_picture, "wb") as pi:
            pi.write(r.content)
            print("save:", save_picture)
        time.sleep(1)     #1秒処理を休止

5. メイン処理

画像を抽出して絶対urlを作成、そのurlを用いて実際に画像をダウンロードする関数を作成する。

def download_pictures():
    html = requests.get(page_url).text
    urls = get_img_urls(html)
    downloads(urls)

6. 実行

以下を追記しデバッグしてみよう。指定したパスにディレクトリが作成され画像のダウンロードが開始する。

if __name__ == "__main__":
    download_pictures()

7. まとめ

今回はスクレイピングによる画像ダウンロードの自動化を行った。ページによってはスクレイピングを禁止しているところもあるので利用規約には十分に注意してほしい。

38
70
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
70