1
1

Python3でスクレイピング〜ブラウザ起動編〜

Last updated at Posted at 2023-09-18

はじめに

MacBookを新しく購入したので、Python3を学習しようと思いました。
前回はPython3のインストールからPATHを通すまでを実施しました。

今回はスクレイピングの準備段階として Chromeを立ち上げるところまでやってみます。

開発環境

OS: macOS Monterey(バージョン 12.2.1)
チップ: Apple M1
エディター:Visual Studio Code

デスクトップにフォルダを作成し、その中で任意のファイルを作成します。
今回はget_data.pyとします。

Seleniumのインストール

ターミナルで以下コマンドを実行します。

terminal
% pip install selenium

これで最新バージョンのseleniumをインストールします。

ChromeDriverのインストール

ChromeDriverの公式
上記公式サイトからインストールをします。

ソースコード

get_data.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

def open_browser():
    # ドライバー指定でChromeブラウザを開く
    driver = webdriver.Chrome()

    # Googleに遷移
    driver.get('https://www.google.com/')
    # 5秒間待機
    time.sleep(5)

    # 全てのウインドウを閉じる
    driver.quit()

# 関数の実行
open_browser()

動作確認

ターミナルで以下コマンドを実行します。

terminal
% python get_data.py

すると…

スクリーンショット 2023-09-18 17.18.51.png

Googleが表示されました!
お疲れ様でした!

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