Python + Selenium + PhantomJSメモ
seleniumでボタンをクリックしたいとき
driver.find_element_by_link_text("文字列").click()
で行うがそれでもできない時の対処。
要素の検証から該当のボタンを調査すると「onclick=メソッド名」で、find_element_by_link_text()でも要素を掴めない時があった。
その場合以下で対応した。
element = driver.find_element_by_xpath("xpath") onclick = element.get_attribute("onlclick") driver.execute_script(onclick)
指定した要素が表示されるまで待機するには以下を使う
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By url = "hoge" driver = webdriver.PhantomJS() driver.get(url) # 指定した要素が取得できるまで最大30秒間待機する WebDriverWait(self.driver, 30).until(expected_conditions.presence_of_element_located((By.ID, "ID_NAME")))
href="javascript:void(0)"をxpathで指定する
例:class=hoge配下の要素を取得したい
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait url = "hoge" driver = webdriver.PhantomJS() driver.get(url) target_contents = driver.find_elements_by_xpath("//*[@class='hoge']/a[starts-with(@href, 'javascript:void(0)')]") for target_content in target_contents: # 処理