LoginSignup
0
2

More than 1 year has passed since last update.

Seleniumをローカルで動かす (python)

Posted at

記載日:2022/11/14
pythonでseleniumを実行してみます。

目標(7分)

pythonでSeleniumを実行し、Webサイトの画面を開く。

環境

OS : Ubuntu22.04
Chrome:107.0.5304.110。インストール済。
Chrome Driver:107.0.5304.62。
VSCodeインストール済。
pythonインストール済。
(私の環境ではpyenvをインストールしたので、python使える状況。)
※pyenvのインストール方法はこちら

作業

0.プロジェクト作成(1分)

プロジェクトフォルダへ移動し、プロジェクトファイルを作成する。
VSCodeを開く。

cd ~/Desktop
mkdir python-test
cd python-test
touch main.py
code .

1.Chrome Driverダウンロード(1分)

Webサイトから、自分のChromeバージョンに一致するドライバーをダウンロードする。私の環境では、Chromeが107.0.5304.~だったので、107.0.5304.62のChrome Driverをダウンロードした。
ダウンロードファイルを解凍し、chromedriver(実行ファイル)をプロジェクトフォルダ内へ移動する。

 python-test
  |
  |-main.py
  |-chromedriver

2.コード記述(5分)

VSCodeでmain.pyに以下を記述。
今回はoptionsを特に設定してないが、headlessなどの設定をここにすることになる。

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options as OptionsC

def main():
    DriverPath="./chromedriver"
    optionsC=OptionsC()
    driver=webdriver.Chrome(DriverPath, options=optionsC)
    driver.get("https://[ドメインやURL]")

    time.sleep(10) #10秒待ち
    driver.close()
    driver.quit()

if __name__=="__main__":
    main()

pipを使ってSeleniumをインストール後、pythonコマンドで本プログラムを実行する。設定したWebサイトが開き、うまく動いたことが分かる。

pip install selenium
python main.py
0
2
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
0
2