7
5

More than 3 years have passed since last update.

PythonでGoogle画像検索から好きなキャラの画像を自動保存する

Posted at

はじめに

以下の記事を参考にGoogle画像検索の結果を上から順に20枚保存するcodeを書きました。大したことしてないです
PythonでGoogle画像検索をして画像をフォルダに保存する

環境

OS:Windows 10 home
言語:python 3.8.1

Code

codeの説明はコメントで行います

download_images.py

# install module
import requests
import random
import shutil
import bs4

# 保存するURLの取得
def image(data,num):
    # Google画像検索のURL取得
    res = requests.get("https://www.google.com/search?hl=jp&q=" + data + "&btnG=Google+Search&tbs=0&safe=off&tbm=isch")
    html = res.text   # text化
    soup = bs4.BeautifulSoup(html,'lxml')   # 整形
    links = soup.find_all("img")   # img elementの取得
    link = links[num].get("src")   # num番目のsrcURLの取得
    return link

# 該当するURLからdownload
def download(url,file_name):
    req = requests.get(url, stream=True)
    if req.status_code == 200:
        with open(file_name + ".png", 'wb') as f:   # pngをbinでfileに書き出し
            req.raw.decode_content = True
            shutil.copyfileobj(req.raw, f)   # fileにpng画像データをコピー

# 検索する子の名前を指名してお出迎え
name = input("お目当ての子は?:")
for i in range(1,20):   # 便宜的に20枚とする
    link = image(name,i)
    download(link,name + str(i))
    print(link)
    i += 1   # 20回繰り返す


結果

山.png

今回は"白銀圭"ちゃんを指名させて頂きました。
"かぐや様は告らせたい" : "妹ヒロイン"

山.png

できました。
とってもお可愛いこと。

圭ちゃんは初回の指名だったので、指名料として3000円取られました(なんのこっちゃ)

今後

美少女を囲ってる感じで大変満足なのですが、Google画像検索がソースなのでpixelが小さかったりします。
また、一度に読み込むsrcが20枚超くらいなので100枚くらい一気にダウンロードできないです(改良すればできるんでしょうけど)

――では、良き2次元ライフを

7
5
1

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
7
5