Web スクレイピングで画像収集
はじめに
www.d-man.site
↑これのWeb スクレイピング編です
主な環境
名前 | バージョン | 備考 |
---|---|---|
Python(Anaconda) | 3.6.5(Anaconda 5.2) | 環境導入はこれ(http://www.d-man.site/entry/2018/06/04/022059) |
Windows | わすれた | Windowsでも試しました |
Mac OS | macOS High Sierra | MacでもWindowsでもどっちでもええよ |
Google Chrome | 66.0.3359.181 | とりあえずChrome |
ChromeDriver | 2.40 | Pythonからブラウザを動かすため |
ChromeDriverインストール
https://chromedriver.storage.googleapis.com/index.html?path=2.40/
↑ここから自分にあったOSの奴をダウンロードするする
そしたら適当なところにフォルダを作り配置します
WIndowsだったらCドライブ直下に「scraping」ってフォルダ作りましょう
↑こんな感じ
終わり
seleniumインストール
conda install -c conda-forge selenium
anaconda Promptでcondaコマンドでインストール
y/n聞かれるのでyと入力
インストールが終わったらChromeDriverを入れたら場所にscraping.pyのファイルを作りましょう
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities #MacOsの場合 #driver = webdriver.Chrome(executable_path="./chromedriver") #Windowsの場合 driver = webdriver.Chrome(executable_path="./chromedriver.exe")
上記のコードをscraping.pyに記述します
python scraping.py
で実行します
こんな感じでChromeが勝手にひらけば成功です。
selenium使い方
URLを指定して開く
URL="https://google.co.jp/" driver.get(URL)#←URLを指定できる
全体だとこんな感じ
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities #MacOsの場合 #driver = webdriver.Chrome(executable_path="./chromedriver") #Windowsの場合 driver = webdriver.Chrome(executable_path="./chromedriver.exe") URL="https://google.co.jp/" driver.get(URL)
htmlを取得する
html=driver.page_source #pageのhtmlを取得する
全体
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from bs4 import BeautifulSoup #htmlを解析するため #MacOsの場合 #driver = webdriver.Chrome(executable_path="./chromedriver") #Windowsの場合 driver = webdriver.Chrome(executable_path="./chromedriver.exe") URL="https://google.co.jp/" driver.get(URL) print(driver.page_source)#html表示
BeautifulSoup
スクレイピングをするためにBeautifulSoupを使います
こんな感じで使います
使い方
soup = BeautifulSoup(driver.page_source, 'html.parser')
指定したタグの要素を全部取る
htmlのタグを指定してすべて取得
soup = BeautifulSoup(driver.page_source, 'html.parser') for img in soup.find_all("img"):#find_all(タグ)で取得 print(img)
全体
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from bs4 import BeautifulSoup #htmlを解析するため #MacOsの場合 driver = webdriver.Chrome(executable_path="./chromedriver") #Windowsの場合 #driver = webdriver.Chrome(executable_path="./chromedriver.exe") URL="https://www.google.co.jp/search?q=doraemon&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiF8PaIvMrbAhUEErwKHdk0Cc0Q_AUICygC&biw=1439&bih=710&dpr=2" driver.get(URL) soup = BeautifulSoup(driver.page_source, 'html.parser') for img in soup.find_all("img"): print(img)
doraemonの画像の検索結果が出ます
Yahoo 画像検索でのスクレイピング
import os import requests # urlを読み込むためrequestsをインポート import time import sys from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities args = sys.argv if (len(args) != 2): sys.exit() search = args[1] URL = 'https://search.yahoo.co.jp/image/search?p='+search+'&dim=large' images = [] # 画像リストの配列 beforheight=0 #読み込む時間を設定する timer=2 #フォルダを作成する if not os.path.exists(search): os.makedirs(search) #Chromeを開く #MacOsの場合 #driver = webdriver.Chrome(executable_path="./chromedriver") #Windowsの場合 driver = webdriver.Chrome(executable_path="./chromedriver.exe") driver.get(URL) time.sleep(timer) while True: while True: #画面を下までスクロールする driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(timer) #スクロールの位置を取得 height = driver.execute_script("return document.body.scrollHeight") #最後の取得されたスクロールの位置と同じならページの下だと判断 if height == beforheight: break beforheight = height try: submitButton = driver.find_element_by_link_text("もっと見る") submitButton.click() time.sleep(timer) except: break soup = BeautifulSoup(driver.page_source, 'html.parser') for link in soup.find_all("img"): if link.get("src").endswith(".jpg"): images.append(link.get("src")) elif link.get("src").endswith(".png"): images.append(link.get("src")) elif link.get("src"): images.append(link.get("src")) i = 0 # imagesからtargetに入れる for target in images: re = requests.get(target) try: with open(search+"/"+search+"-"+str(i)+".jpg", 'wb') as f: f.write(re.content) # .contentにて画像データとして書き込む i+=1 except: print("Error") print(str(i)+"枚数保存完了") # 確認
実行方法
python scraping.py 検索ワード
検索ワードには適当に入れてもええです
python scraping.py doraemon
ってやればdoraemonのフォルダが直下にできてその中に書き込まれます
こんな感じ
ただし一つ問題点があり、
画像サイズが現物のサイズではなく検索エンジンの表示サイズなのでリンクを踏むように改造しなければならないので頑張ります
まあ色々改造してみてください