LoginSignup
3
3

More than 1 year has passed since last update.

Python: Selenium: 自分のMacのChromeブラウザ設定を使って自動WEBサーフィンするプログラミング

Last updated at Posted at 2022-04-20

ただ単にSeleniumを使うのと違うところは、普段使いの自分のCookieや設定を維持したままChromeを自動操縦できることです。
あとは、起動しっぱなしのChromeブラウザを好きに操作できるので、毎回Chromeが立ち上がっては消えてしまう、のを避けられること。試行錯誤しながらコーディングするのに有用です。

手順

MacにChromeをインストールする

まず、SafariなどでWEB検索して普通にChromeをインストールします。

Chromeのメジャーバージョンナンバーを調べる

Chromeを起動して、アドレスバーに chrome://version/ と入力してジャンプすると調べられます。

スクリーンショット 2022-04-20 18.21.41.png

自分のChromeプロファイル名を調べる

これも先ほどの画面の中にあります。

スクリーンショット 2022-04-20 18.25.05.png

Python用Seleniumライブラリとchromedriver-binaryをインストールする

ターミナルから以下のコマンドでインストールします。
Pythonと一緒にインストールされるpipコマンドを使います。

pip install selenium chromedriver-binary==100.*

chromedriver-binaryは、バージョンを指定します。
指定するナンバーは、先ほど調べたChrome本体のメジャーバージョンと合わせたものです。

Chromeをデバッグポート有効状態で起動する

  1. まず、今デスクトップで起動しているChromeを全て完全に終了させます。
  2. 次に、ターミナルから以下のコマンドでChromeを起動します。
    Chrome実行ファイルのパスは、皆さんの環境に合わせて書き換えてください。
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --profile-directory="Default"

--profile-directory オプションには、先ほど調べた自分のChromeプロファイル名を設定します。

何かエラーログが出るかもしれませんが、多分大丈夫です。
ちゃんと起動できているか確認するには、アドレスバーに http://localhost:9222/json と入力してジャンプしてみてください。
↓こういう画面が出ればOKです。
スクリーンショット 2022-04-20 18.57.21.png

ChromeをSeleniumで自動操縦するプログラムを実行する

以下のサンプルプログラムは、

  1. Google検索にジャンプして、
  2. ちいかわ うさぎ と検索して、
  3. 1ページ目の検索結果の中からランダムに1つ選んでジャンプします。

↓ この箇所は、皆さんの環境に合わせて書き換えてください。
(pipでインストールしたなら、ほとんど一緒だとは思いますが)

executable_path="/opt/homebrew/lib/python3.9/site-packages/chromedriver_binary/chromedriver",
import random
import time

import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait

def main():
    options = webdriver.ChromeOptions()

    # iPhoneXをエミュレートした画面で実行する
    mobile_emulation = {"deviceName": "iPhone X"}
    options.add_experimental_option("mobileEmulation", mobile_emulation)

    # ポート9222でデバッグ通信を待ち受けているChromeを操作する
    options.add_argument("--remote-debugging-port=9222")

    driver = webdriver.Chrome(
        options=options,
        executable_path="/opt/homebrew/lib/python3.9/site-packages/chromedriver_binary/chromedriver",
    )

    search_word = "ちいかわ うさぎ"

    try:
        # 新しいタブを作成する
        driver.execute_script("window.open()")

        # 新しいタブに切り替える
        time.sleep(1)
        driver.switch_to.window(driver.window_handles[-1])

        driver.get("https://www.google.com/")

        wait = WebDriverWait(driver, 10)

        # 検索テキストボックスがレンダリングされるまで待つ
        locator_search_textbox = (By.CSS_SELECTOR, "input[title=検索]")
        wait.until(expected_conditions.visibility_of_element_located(locator_search_textbox))

        # 検索ワードを入力する
        driver.find_element(*locator_search_textbox).clear()
        driver.find_element(*locator_search_textbox).send_keys(search_word)

        # 検索ボタンを押す
        # driver.find_element(By.NAME, "btnK").click() # 上にdivとかが被ってると発動しなかったりする
        driver.execute_script('document.querySelector("input[name=btnK]").click();')

        # 検索結果画面の結果エリアがレンダリングされるまで待つ
        wait.until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "div.main")))

        # 検索結果のリンク要素を取得
        links_search_result = driver.find_elements(By.CSS_SELECTOR, "h3.LC20lb")

        # 検索結果のリンクが1つ以上あったら、ランダムにクリックする
        if links_search_result:
            links_search_result[random.randint(0, len(links_search_result)-1)].click()
    finally:
        driver.quit()


main()

どうでしょう。
うまくいきましたでしょうか。
自分のデスクトップで起動しているChromeが、勝手に検索して勝手にジャンプする動きが目視できたかと思います。

スクリーンショット 2022-04-20 18.50.19.png
3
3
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
3
3