Effective Computer Science - 頂は礎の上に -

新しい技術の多くは基礎的な技術の上に成り立っています。激動の技術変化に耐えうる体系知識の習得を目的に「基礎と実践の架け橋」となるサイトを目指します。

【Python&Selenium】aタグがクリックできない

Python & Seleniumnでヘッドレスオプションをつけた状態(options.add_argument('--headless'))でaタグをクリックしようとすると以下のようなエラーが発生することが稀にある。 付近のspanタグをクリックしてしまうようだ。

...a> is not clickable at point (257, 862). Other element would receive the click: <span...

Debugging "Element is not clickable at point" error - Stack Overflow によるchromeのバグで修正される見込みはないらしい。

解決策としては、3つ。

1. HREFを取得してdriver.getでアクセスする

url = driver.find_element_by_link_text("リンクテキスト").get_attribute("href")
driver.get(url)

2. 該当aタグのインデックスを取得して、JSでクリック(1がうまくいかない場合)

soup = BeautifulSoup(driver.page_source, 'html.parser')
for i, a_tag in enumerate(soup.find_all('a')):
    if a_tag.text == 'リンクテキスト':
        driver.execute_script("document.getElementsByTagName('a')[" + str(i) + "].click();")
        break

3. クリックを受け取ってしまっている要素を隠す

driverでclickを行う前に、javascriptでクリックの邪魔をしている要素を隠します。

driver.execute_script("document.getElementsByClassName('submit_area')[0].style.visibility='hidden';")