ページが完全に読み込まれる前に、Seleniumで要素をクリックしてデータをスクレイピングするにはどうすればよいですか?私のインターネット接続はかなりひどいので、ページを完全にロードするのに時々永遠にかかることがあります、とにかくこれの周りにありますか?
ChromeDriver 77.(Chromeバージョン77をサポート)がeager
をサポートするようになりました pageLoadStrategy。
解決した問題1902:熱心なページ読み込み戦略をサポート[Pri-2]
あなたが質問するようにclick on elements and scrape data before the page has fully loaded
この場合、属性pageLoadStrategy
を利用できます。 Seleniumがデフォルトでページ/ URLをロードするとき、それはpageLoadStrategy
がnormal
に設定されたデフォルト設定に従います。 Seleniumは、異なるDocument readiness state
。現在、Seleniumは3つの異なるDocument readiness state
pageLoadStrategy
を使用して、次のように構成できます。
none
(未定義)eager
(ページがインタラクティブになります)normal
(完全なページの読み込み)pageLoadStrategy
を構成するコードブロックは次のとおりです。
from Selenium import webdriver
from Selenium.webdriver.common.desired_capabilities import DesiredCapabilities
binary = r'C:\Program Files\Mozilla Firefox\firefox.exe'
caps = DesiredCapabilities().FIREFOX
# caps["pageLoadStrategy"] = "normal" # complete
caps["pageLoadStrategy"] = "eager" # interactive
# caps["pageLoadStrategy"] = "none" # undefined
driver = webdriver.Firefox(capabilities=caps, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
driver.get("https://google.com")
Chromedriverの場合、@ DebanjanBの回答と同じように機能しますが、「熱心な」ページロード戦略は まだサポートされていません です。
したがって、chromedriverの場合は次のようになります。
from Selenium import webdriver
from Selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities().CHROME
# caps["pageLoadStrategy"] = "normal" # Waits for full page load
caps["pageLoadStrategy"] = "none" # Do not wait for full page load
driver = webdriver.Chrome(desired_capabilities=caps, executable_path="path/to/chromedriver.exe")
「なし」戦略を使用する場合、必要な要素がロードされているかどうかを確認するために、独自の待機メソッドを実装する必要があることに注意してください。
from Selenium.webdriver.common.by import By
from Selenium.webdriver.support.ui import WebDriverWait
from Selenium.webdriver.support import expected_conditions as ec
WebDriverWait(driver, timeout=10).until(
ec.visibility_of_element_located((By.ID, "your_element_id"))
)
これで、ページが完全に読み込まれる前に、要素との対話を開始できます。