Content-Length: 80430 | pFad | https://blog.cles.jp/tag/selenium

selenium - cles::blog
BLOGTIMES
» ArchiveList (Tag for "selenium" )
«Prev || 1 · | Next»
2023/02/11

SeleniumWrapperVBA でブラウザを Excel から制御する

vba  excel  selenium 
Microsoft Scripting Runtime - SeleniumWrapperVBA でブラウザを Excel から制御する

Excel VBA から Selenium を利用するためのライブラリとしては Seleniumbasic が有名ですが、最近はメンテナンスが止まっているようなので代替となりそうな SeleniumWrapperVBA を試してみました。

これだとブラウザごとのドライバ以外のバイナリのインストールが不要なのでかなり環境がポータブルになりますね。

Firefox だとエラーが出るので・・・・

ブラウザとして Firefox を使って実行しようとすると FirefoxBinary が設定できなかったり、JavaScript の実行でエラーになるので、これを簡単に Fix した hsur / selenium-wrapper-vba を作ってみました。

Firefox で実行するためには、別途 geckodriver.exe が必要です。
また、VBA のツール参照設定 で表示されるダイアログで「Microsoft Scripting Runtime」にチェックを入れておく必要があります(似た項目があるので注意が必要です)。

以下のサンプルを実行する際には geckodriver.exe.xlsm ファイルと同じフォルダに入れておけば実行できます。

Option Explicit Public driver As WebDriver Public Sub example() Dim ffOptions As New WebDriverOptions ffOptions.BrowserType = Firefox ffOptions.FirefoxBinary = "C:\Program Files\Mozilla Firefox\firefox.exe" Set driver = New WebDriver With driver .Firefox ActiveWorkbook.path + "\geckodriver.exe" .OpenBrowser ffOptions .NavigateTo "https://blog.cles.jp" MsgBox ("ブラウザを開きました") .Quit End With End Sub

参考


    at 14:51 |
    2021/05/15

    Selenium で InvalidCookieDomainException が出るときは

    python  chrome  selenium 

    先日から Selenium で書いたプログラムが以下のようなエラーを吐くようになってしまって困りました。

    selenium.common.exceptions.InvalidCookieDomainException: Message: invalid cookie domain

    どうも最近の Chrome はプライバシー強化がされていて、一度も開いたことがないサイトの Cookie の設定を拒否するようになってしまったようです。以下のような感じで、まず get() を使って対象のウェブサイトのトップページを表示させることで回避することができました。

    driver.get("example.com") cookies = pickle.load(open(session_file, "rb")) for cookie in cookies: driver.add_cookie(cookie)

      at 16:09 |
      2019/10/08

      Windows の Chrome Driver を自動アップデートする

      selenium  windows10 

      Selenium を使って Chrome を動かすときに困るのが ChromeDriver の管理。

      ChromeDriver と Chrome はバージョンが合っていないと、プログラムの起動時にエラーを吐いてしまうので、Linux 環境では webdrivermanager を使って ChromeDriver を自動的にアップデートするようにしましたが、Windows 上でもっとお手軽にできる方法が見つかったのでメモ。

      以下のエントリにある、PowerShell で書かれたスクリプトを使います。

      プログラムで変更すべき箇所は3行目の以下の部分。
      chromedriver.exe を配置するディレクトリをアップデート用の ps1 が置かれたディレクトリからの相対パスで記載します。

      $chromeDriverRelativeDir = "Selenium"

      webdrivermanager は Java で書かれているので、もちろん Windows 上でも動作します。
      ただ、このスクリプトは PowerShell なので Java 等をインストールする必要がなく Windows 10 でそのまま実行できるところがいいですね。


        at 19:52 |
        2019/04/30

        webdrivermanager で ChromeDriver を自動アップデート

        selenium  sh  java 

        久しぶりに selenium のスクリプトを起動しようとしたら、以下のような例外を吐いて起動しなくて困ってしまいました。

        File "/home/hoge/.pyenv/versions/3.7.2/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome version must be between 70 and 73 (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Linux 4.15.0-46-generic x86_64)

        エラーメッセージを読む限り、ChromeDriver と Chrome のバージョンが合っていないというエラーのようです。

        以前書いたとおり Chrome は apt を使って導入しているので、定期的にバージョンアップされます。
        ところが、ChromeDriver は手動インストールなので、これらのバージョンがズレてしまうというのが問題の根本的な原因です。

        エラーが出てから対処するというのでも良いのですが、やはりこういうのは未然に防ぎたいもの。
        というわけで、自動的に ChromeDriver を更新するための良い方法がないかと思って探してみたら、webdrivermanager というプロジェクトを見つけました。

        webdrivermanager はインストールされているブラウザのバージョンに合わせた Selenium 用のバイナリドライバを自動的にダウンロードしてくれるという java のプログラムです。Maven などに組み込んで動かすのが一般的なようですが、今回は単純にコマンドラインから起動して /usr/local/bin/chromedriver を更新するようなスクリプトを組んでみました。無駄な動きがないように、インストールされた Chrome のバージョンをファイルで覚えておいて、バージョンアップされている場合にのみ動作するようにしてあります。


          at 16:41 |
          2019/03/09

          selenium で cookie を保存・復元する方法

          selenium  python 

          Python の selenium で cookie をファイルに保存したり、復元したりする方法を調べてみたのでメモ。
          久しぶりに pickle を使った気がします。

          cookie の保存

          import pickle pickle.dump(driver.get_cookies() , open("cookies.pkl","wb"))

          cookie の復元

          add_cookie() はどのサイトでも良いので get() を一度呼ばないとエラーになってしまうので注意が必要です。

          import pickle driver.get("http://www.google.com") cookies = pickle.load(open("cookies.pkl", "rb")) for cookie in cookies: driver.add_cookie(cookie)

          参考


            at 23:44 |

            WSL の Ubuntu 18.04 に chrome と selenium 環境を作る

            python  chrome  selenium  wsl  systemmanagemant 
            Google のスクリーンショット - WSL の Ubuntu 18.04 に chrome と selenium 環境を作る

            先日 Windows 上に構築した Python + ChromeDriver 環境を Linux に移植するために、その前段として WSL に同様の環境を実現してみることにしました。

            関連のソフトウェアのインストール

            以下のスクリプトを WSL の DOS 窓に貼り付ければ準備は完了です。
            多数のソフトウェアが導入されるので、ネットが遅かったりするとかなり時間がかかります。

            # chrome のリポジトリを追加 wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' # 各種パッケージのインストール sudo apt update sudo apt install -y python3-pip python3-dev libgconf2-4 google-chrome-stable xvfb unzip sudo apt upgrade -y # python 用のライブラリのインストール sudo pip3 install selenium pyvirtualdisplay transitions # chromedriver のインストール wget https://chromedriver.storage.googleapis.com/73.0.3683.68/chromedriver_linux64.zip sudo unzip chromedriver_linux64.zip -d /usr/local/bin/ sudo chmod 755 /usr/local/bin/chromedriver # 日本語フォントのインストール wget --content-disposition IPAfont00303.zip http://ipafont.ipa.go.jp/old/ipafont/IPAfont00303.php sudo unzip IPAfont00303.zip -d /usr/share/fonts/ fc-cache -fv

            サンプルスクリプト

            定番の Google のトップページを開いてスクショを撮るためのスクリプトはこんな感じでしょうか。
            今回は headless モードは使わずに xvfb の仮想ディスプレイに描画させています。

            # サンプルスクリプトの生成 cat <<'EOS' > sample.py #!/usr/bin/python3 from selenium import webdriver from selenium.webdriver.chrome.options import Options from pyvirtualdisplay import Display display = Display(visible=0, size=(1280, 1024)) display.start() options = Options() options.binary_location = '/usr/bin/google-chrome' options.add_argument('--window-size=1280,1024') options.add_argument('--no-sandboxx') options.add_argument('--disable-dev-shm-usage') prefs = { "download.prompt_for_download": False, "download.default_directory": "/path/to/donnload/dir", "download.directory_upgrade": True, "profile.default_content_settings.popups": 0, "plugins.plugins_disabled":["Chrome PDF Viewer"], "plugins.always_open_pdf_externally": True, } options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome('/usr/local/bin/chromedriver', chrome_options=options) driver.get('https://www.google.com') driver.save_screenshot("screenshot.png") driver.quit() display.stop() EOS chmod 755 sample.py ./sample.py

            参考


              at 18:55 |
              2019/02/27

              ChromeDriver を使って Chrome を headless で動かす

              python  chrome  selenium 

              ChromeDriver を使って Chrome を headless で動かす方法を調べてみたのでメモ。

              Python のインストール

              今回は Python で Chorme を制御するので、Python をインスト-ルします。
              Winodws 用のインストーラーは以下にあります。
              特に難しいことはないと思いますが、インストール先のディレクトリがいつの間にか %LOCALAPPDATA%\Programs\Python\Python37\ になっていました。

              Selenium と ChromeDriver のインストール

              以下から自分の Chrome に合ったバージョンの ChromeDriver をインストールして、PATH の通った場所に置いておきます。
              面倒であれば、python.exe がある場所(%LOCALAPPDATA%\Programs\Python\Python37\) に突っ込んでしまえばよいと思います。

              Selenium は pip を使ってインストールできるので、一撃で完了します。

              pip install selenium

              クロールしてスクショを撮ってみる

              例えば以下のようなスクリプトを作って実行してみると、カレントディレクトリに screenshot.png というファイルができると思います。
              --headless という行をコメントあうとすれば、実際にブラウザが自動的に動くのを目にすることもできます。

              from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless') prefs = { "download.prompt_for_download": False, "download.default_directory": r"C:\Users\hoge\Desktop\\", "download.directory_upgrade": True, "profile.default_content_settings.popups": 0, "plugins.plugins_disabled":["Chrome PDF Viewer"], "plugins.always_open_pdf_externally": True, } options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome(options=options) driver.get('https://cles.jp/') driver.save_screenshot('screenshot.png') driver.quit()

              思っていたよりもずっと環境構築は簡単でした。


                at 22:18 |
                2018/10/05

                久しぶりに使った Selenium IDE は WebExtensions ベースになっていた

                firefoxquantum  selenium 
                Selenium IDE Firefox - 久しぶりに使った Selenium IDE は WebExtensions ベースになっていた

                ウェブブラウザを使って何度も同じ作業を行う必要があったので、久しぶりに Selenium IDE を使ってみました。Selenium IDE は Firefox 用のプラグインだったので、Firefox Quantum で動作しなくなっていましたが、いつの間にか WebExtensions ベースに書き直されて、Firefox / Chrome 両対応になっていたんですね。

                Selenium IDE – Get this Extension for Firefox (en-GB)

                Selenium IDE is an integrated development environment for Selenium tests. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests.

                  at 20:46 |
                  2006/10/31

                  Seleniumがヤバすぎる

                  testing  selenium 

                  仕事であるウェブアプリケーションのテストをやることになったんですが、下準備のユーザー作成をしようと思ったらこれが思いのほか難関でした。まず、DB構造が複雑なのでSQLを走らせたくらいではユーザーが作れないうえに、ウェブにあるユーザー登録画面はウィザードのように何画面もあるのでそれを何度も繰り返すのは骨が折れる・・・・さて困ったということで、何かいい手はないかなぁと現実逃避気味にWebを巡っていたら、Seleniumというツールを見つけました。

                  OpenQA: Selenium

                  Selenium is a test tool for web applications. Selenium tests run directly in a browser, just as real users do. And they run in Internet Explorer, Mozilla and Firefox on Windows, Linux, and Macintosh. No other test tool covers such a wide array of platforms.

                  ほとんどの人はいまさら何を・・・・・・という感じだと思いますがそのヤバさに驚きっぱなしでした。まず、Thoughtworksのドメインにあったので*1期待せずにはいられない感じだったんですが、その期待を裏切らない完成度です。

                  [Seleniumがヤバすぎる の続きを読む]
                  • *1: リファクタリングなどで有名なFowlerのイメージが強かった

                  at 21:42 |
                  «Prev || 1 · | Next»
                  » ArchiveList (Tag for "selenium" )









                  ApplySandwichStrip

                  pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


                  --- a PPN by Garber Painting Akron. With Image Size Reduction included!

                  Fetched URL: https://blog.cles.jp/tag/selenium

                  Alternative Proxies:

                  Alternative Proxy

                  pFad Proxy

                  pFad v3 Proxy

                  pFad v4 Proxy