SeleniumでChromeheadlessを使う際に要素がVisibleにならずTimeOutになってしまう
とあるaタグのhref要素を取得したい。Pythonで書いています。
button = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.ID, "id-of-element"))) detail_menu_url = detail_menu_button.get_attribute("href")
しかしChromeのheadlessモードを使う際、実際に手元のブラウザでは要素を取得できるのにheadlessモードにした途端、要素にアクセスできず以下のようなタイムアウトエラーが出ていました。
2019-04-08T09:40:08.451051+00:00 app[run.3736]: Traceback (most recent call last): 2019-04-08T09:40:08.451085+00:00 app[run.3736]: File "app.py", line 134, in <module> 2019-04-08T09:40:08.451471+00:00 app[run.3736]: main() 2019-04-08T09:40:08.451477+00:00 app[run.3736]: File "app.py", line 129, in main 2019-04-08T09:40:08.451753+00:00 app[run.3736]: pay_money, pay_amount, pay_day = confirm_card_payment() 2019-04-08T09:40:08.451760+00:00 app[run.3736]: File "app.py", line 93, in confirm_card_payment 2019-04-08T09:40:08.452013+00:00 app[run.3736]: detail_menu_button = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "toDetailsDetailRelayFirst"))) 2019-04-08T09:40:08.452038+00:00 app[run.3736]: File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/support/wait.py", line 80, in until 2019-04-08T09:40:08.452257+00:00 app[run.3736]: raise TimeoutException(message, screen, stacktrace) 2019-04-08T09:40:08.452322+00:00 app[run.3736]: selenium.common.exceptions.TimeoutException: Message:
うーん。つまりどれだけ待ってもvisibleにならない=Chromeheadlessには見えていないということか。検索して解決策発見。
I think the problem is, that the Element is really not visible in the default viewbox (600x800) of Headless Chrome.
なるほど。Windowサイズを指定しよう。
options.add_argument('window-size=1200,1100')