LoginSignup
11
20

More than 3 years have passed since last update.

webスクレイピングで画像を保存する

Last updated at Posted at 2020-02-02

概要

webサイト上の画像を、PythonのrequestsとBeautifulSoupを使ってPC上に保存します。ついでにスクリプトを実行時に画像を表示します。

動機

Perfumeの画像を保存したいです。自動で保存できれば便利だと思いました。

開発

環境

OS Windows 10
Python 3.7.3
requests 2.22.0
beautifulsoup4 4.8.2

完成したコード

main.py
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import cv2

root = "https://www.perfume-web.jp/"
url = "https://www.perfume-web.jp/index-jpn.php"
store_path = "PATH"

def img_store(path):p
    img = requests.get(path).content

    print(path)

    with open(store_path, "wb") as f:
        f.write(img)

    img_local = cv2.cvtColor(cv2.imread(store_path), cv2.COLOR_BGR2RGB)

    plt.imshow(img_local)
    plt.show()

response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

top_img = soup.find("div", id="main").find("img").get("src")

img_store(root+top_img)

説明

response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

top_img = soup.find("div", id="main").find("img").get("src")

指定したURLからHTMLを抽出します。(1,2行目)
次に、サイトのHTMLを読みます。方法は、Chromeなら左クリックして、「検証」を選択すると出てくるウィンドウで読めます。

今回はWEBページのトップ画像を取りたいので、divタグのmainを指定しました。
find()は同じタグやidがあっても一番最初に出てくるもののみを取ってくるので、帰ってくる値は1つのみです。その中のimgタグのsrcを取得しました。

HTML内のタグやidは実際にサイトとHTMLを読んで自分で工夫して見つけるしかありません。より複雑な要素を獲得するためにbs4に多くの関数が用意されています。

 top_img = soup.find("div", id="main").find("img").get("src")

def img_store(path):p
    img = requests.get(path).content

    print(path)

    with open(store_path, "wb") as f:
        f.write(img)

    img_local = cv2.cvtColor(cv2.imread(store_path), cv2.COLOR_BGR2RGB)

    plt.imshow(img_local)
    plt.show()

画像のパスが相対パスだったのでサイトのドメインをrootとして用意して、取得した画像の相対パスと接続することで画像の正しいURLを作りました。
あとは保存と表示です。matplotlibで表示したのは趣味です。ピクセル数に応じた目盛りが出ていい感じです。

結果

スクリーンショット (7).png
こんな感じに表示されます。(3人のご尊顔は隠させていただきました。見たい方はPerfume Official Siteへどうぞ)
画像の探し方を変えれば他の画像も保存できます。

考察

自動的にサイトの更新がわかればいいなーという考えの足掛かりにwebスクレイピングをしてみました。webスクレイピングにはルールや法律など、いろいろあるらしいので、下記のサイトを参考になさってください。相手のサーバに負荷をかけてしまうのは攻撃の一種ですよね。。。
https://qiita.com/nezuq/items/c5e827e1827e7cb29011
デバッグや練習では、一度サイトのHTMLをすべて保存して使うのがよいと思います。思いがけない無限ループなどしたら恐ろしい。

参考

http://kondou.com/BS4/
https://qiita.com/Azunyan1111/items/9b3d16428d2bcc7c9406
https://qiita.com/YosukeHoshi/items/189c615187f41f2f4e27

11
20
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
11
20