前提
- スクレイピングの際に、使用するプロファイルを指定しつつヘッドレスでブラウザを操作したいが、ヘッドレスモードにすると指定したelementを取得できない
- options.add_argument('--headless')の記述がなければ正常に動く
- browser.get("url")の遷移先はログインが必要なサイト
- 遷移先をログイン不要のサイトにすると正常にelementを取得できる
以上のことから、エラーの原因は--user-data-dirの部分が機能しておらず、指定したurlがログイン前のページに飛んでいるからだと思われます。
どうすれば使用するプロファイルを指定しつつ、ヘッドレスでブラウザを操作できるのでしょうか?
発生している問題・エラーメッセージ
Message: no such element: Unable to locate element: {"method":"xpath","selector":"指定したxpath"} (Session info: headless chrome=103.0.5060.134)
該当のソースコード
python
1from selenium import webdriver 2from selenium.webdriver.chrome.options import Options 3 4options = webdriver.ChromeOptions() 5 6options.add_argument('--user-data-dir=' + "ユーザーデータディレクトリのパス") 7options.add_argument('--profile-directory=' + "プロファイルディレクトリ名") 8options.add_argument('--headless') 9 10browser = webdriver.Chrome(options=options) 11browser.get("url") 12 13elem = browser.find_element_by_xpath("指定したxpath") 14browser.implicitly_wait(10) 15elem.click()
試したこと
https://blog.sbfm.jp/archives/196
https://teratail.com/questions/142395
あなたの回答
tips
プレビュー