Seleniumを使用しPythonでWebページのタイトルを取得してみます。
Seleniumモジュールは、Pythonの標準ライブラリではありませんので、事前にインストールしておく必要があります。またGoogleChromeを使用する場合は、chromedriver-binaryも必要になりますので、これも事前にインストールしておく必要があります。
■Python
今回のPythonのバージョンは、「3.8.5」を使用しています。(Windows10)(pythonランチャーでの確認)
■chromedriver-binaryのバージョン
chromedriver-binary==87.0.4280.88.0
■GoogleChromeのバージョン
バージョン: 87.0.4280.88(Official Build) (64 ビット)
■Seleniumを使用しWebページのタイトルを取得する
では、早速Seleniumを使用しWebページのタイトルを取得するスクリプトを書いていきます。
■コード
from selenium import webdriver import chromedriver_binary driver = webdriver.Chrome() url = "https://laboratory.kazuuu.net/" driver.get(url) get_title = driver.title print(get_title)
seleniumのwebdriverと、chromedriver_binaryを呼び出して、driverという変数を作成し、「webdriver.Chrome()」でChrome用WebDriverを指定します。
次にurlという変数を作成し、その中にタイトルを取得したいWebページを格納します。今回は当サイト(https://laboratory.kazuuu.net/)を指定しています。
格納後、driver.get()でChrome用WebDriverで指定したWebページを開きます。
開いた後に、get_titleという変数を作成し、driver.titleでWebページのタイトルを格納します。
格納したタイトルをprint関数で出力します。
■実行
今回のスクリプトを「webpage_title.py」という名前で保存し、コマンドプロンプトから実行してみます。
実行してみると、GoogleChromeが起動し、指定したWebページにアクセスし、タイトルを取得し、コマンドプロンプト上に出力されることを確認できました。
■備考1
[17948:14848:1206/083652.959:ERROR:device_event_log_impl.cc(211)] [08:36:52.959] USB: usb_device_handle_win.cc:1020 Failed to read descriptor from node connection: システムに接続されたデバイスが機能していません。 (0x1F)
[17948:14848:1206/083653.186:ERROR:device_event_log_impl.cc(211)] [08:36:53.186] Bluetooth: bluetooth_adapter_winrt.cc:1073 Getting Default Adapter failed.
今回スクリプトを実行すると、上記のエラーが表示されました。調べてみると、コンピュータの一部の機能を停止して省電力モードで待機(サスペンド)されているUSBデバイスのプロパティをChromeが読み取ろうとすることによって引き起こされるのが原因のようです(https://stackoverflow.com/questions/65080685/usb-usb-device-handle-win-cc1020-failed-to-read-descriptor-from-node-connectio)。
WebUSBでデバイスへの接続に問題がない場合は、これらの警告を無視しても問題はないようです。
■備考2
今回、GoogleChromeを使用するために、スクリプト上でchromedriver-binaryをインポートしましたが、「import chromedriver_binary」という記述がないと下記のエラーが発生しました。
Traceback (most recent call last):
File “C:\pg\Python38\lib\site-packages\selenium\webdriver\common\service.py”, line 72, in start
self.process = subprocess.Popen(cmd, env=self.env,
File “C:\pg\Python38\lib\subprocess.py”, line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File “C:\pg\Python38\lib\subprocess.py”, line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] 指定されたファイルが見つかりません。During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:\Users\user\webpage_title.py”, line 3, in <module>
driver = webdriver.Chrome()
File “C:\pg\Python38\lib\site-packages\selenium\webdriver\chrome\webdriver.py”, line 73, in __init__
self.service.start()
File “C:\pg\Python38\lib\site-packages\selenium\webdriver\common\service.py”, line 81, in start
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: ‘chromedriver’ executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
コメント