【selenium】seleniumを使ってGoogleのタイトルを取得してみる【python3】

selenium

Macでの環境構築

python3のインストール

 brew install python@3

python3のバージョン確認

python3 --version
Python 3.11.6

seleniumインストール

pip3 install selenium

seleniumのバージョン確認

pip3 show selenium

>Name: selenium
>Version: 4.14.0

現在のブラウザ(chrome)のバージョンを調べる verは118

chromeのバージョン118に合うchromedriverのバージョンを調べてダウンロードし、適当なディレクトリに配置する

https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/118.0.5993.70/mac-x64/chromedriver-mac-x64.zip

pythonコードを書く、今回はGoogleにアクセスし、タイトルを出力する簡単なもの

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

# chromedriver.exeがある場所
driver_path = "/Users/yuki/chromeDriver/chromedriver"

# webdriverの作成
service = Service(executable_path=driver_path) 
driver = webdriver.Chrome(service=service)

driver.get("https://www.google.co.jp/")

# ウェブページのタイトルを取得
title = driver.title
print("ウェブページのタイトル:", title)

# WebDriverを閉じる
driver.quit()

python実行

python3 ./firstselenium.py

無事ブラウザが起動し、Googleにアクセス後タイトルが出力されました

タイトルとURLをコピーしました