【Mac】PythonとSelenium(4以上)でブラウザを自動操作(クローリング/スクレイピング)

■参考URL

https://tanuhack.com/selenium/

Seleniumをインストールする

python3 -m pip install selenium

WebDriverをダウンロードする

https://chromedriver.chromium.org/home

から、使っているchromeのバージョンにあったものをダウンロード

モジュールのインポート

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

WebDriverのオプション設定

# Seleniumをあらゆる環境で起動させるChromeオプション
options = Options()
options.add_argument('--disable-gpu');
options.add_argument('--disable-extensions');
options.add_argument('--proxy-server="direct://"');
options.add_argument('--proxy-bypass-list=*');
options.add_argument('--start-maximized');
# options.add_argument('--headless'); # ※ヘッドレスモードを使用する場合、コメントアウトを外す

WebDriver(ブラウザ)の起動

DRIVER_PATH = '{{ WebDriverのパスを指定(絶対でも相対パスでも可) }}'
# DRIVER_PATH = '/Users/Kenta/Desktop/Selenium/chromedriver' # ローカル
# DRIVER_PATH = '/app/.chromedriver/bin/chromedriver'        # heroku

# ブラウザの起動
driver = webdriver.Chrome(executable_path=DRIVER_PATH, chrome_options=options)

Webページにアクセス

# Webページにアクセスする
url = '{{ クローリング/スクレイピングするURL }}'
driver.get(url)

Selenium4ではfind_element_by_id、nameは非推奨

http://holiday-programmer.net/selenium_ver_check/

pip listコマンドで確認

pip list

idから参照

driver.find_element_by_id("age_2").click() ※旧Ver
driver.find_element(By.ID,"sex_2").click() ※新Ver

** 参考URL

https://www.youtube.com/watch?v=6YnFP1Lt610

PythonSelenium:「Chromeは自動テストソフトウェアによって制御されています」を消す方法

https://office54.net/python/scraping/selenium-chrome-status

PythonSelenium:ブラウザ操作して静的・動的(Ajaxjavascript)ページから情報を取得

https://office54.net/python/module/python-selenium-chrome

PythonSeleniumを使ってChromeを操作するための基礎(自動化)

https://reffect.co.jp/python/selenium

ChromeDriver に PATHを通していない場合のエラーの対処方法

https://laboratory.kazuuu.net/close-a-specific-web-page-in-python-using-selenium/

PythonSeleniumChrome操作時に出るエラーメッセージ「システムに接続されたデバイスが機能していません。 (0x1F)」の消し方

https://qiita.com/kabocha_1220/items/6d2f819acf3f62a26613

Python】send_keys・・・キーボード入力をする(通常キー)

https://www.seleniumqref.com/api/python/element_set/Python_send_keys.html

PythonEXCELの最大行・最大列を取得する

https://pg-chain.com/python-excel-row-column

Python エクセル】空白セル(None)をIF文で判定する方法

https://office54.net/python/excel/python-cell-none

Pythonの関数や条件分岐で何もしない場合の書き方を現役エンジニアが解説【初心者向け】

https://techacademy.jp/magazine/36304

タイプ「datetime.date」のオブジェクトには、Pythonでlen()」がありません

https://stackoverflow.com/questions/52846048/object-of-type-datetime-date-has-no-len-in-python