我想使用 Python 和 Selenium從https://www.dividend.com/dividend-champions/獲取公司名稱。
但是列印一些公司名稱后會出現以下錯誤。
StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
我怎樣才能避免這個錯誤?
奇怪的是,在發生此錯誤之前會列印一些公司名稱。
如果您能給我一些提示,將不勝感激。
Python
driver.get('https://www.dividend.com/dividend-champions/')
companies = driver.find_elements(by=By.CLASS_NAME, value="m-table-long-name")
print(len(companies)) #30
for company in companies:
print(company.text)
uj5u.com熱心網友回復:
StaleElementReferenceException表示所選元素可能不再在 html dom 中。但是,此例外背后有很多原因,例如不正確的元素選擇、加載時間等。所以你需要使用webdriverwait.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
option = webdriver.ChromeOptions()
option.add_argument("start-maximized")
#chrome to stay open
option.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=option)
driver.get('https://www.dividend.com/dividend-champions/')
names = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//*[@]/div[@]')))
for name in names:
company = name.find_element(By.XPATH,'.//a[@]').text
print(company)
輸出:
Eversource Energy
Andersons Inc.
J.M. Smucker Co.
Cambridge Bancorp
Factset Research Systems Inc.
Graco Inc.
First Of Long Island Corp.
Stepan Co.
MDU Resources Group Inc
W. P. Carey Inc
Church & Dwight Co., Inc.
Lincoln Electric Holdings, Inc.
Matthews International Corp. - Ordinary Shares - Class A
New Jersey Resources Corporation
Bank OZK
Caterpillar Inc.
Brown & Brown, Inc.
Carrier Global Corp
Polaris Inc
International Business Machines Corp.
NextEra Energy Inc
Realty Income Corp.
RenaissanceRe Holdings Ltd
Cullen Frost Bankers Inc.
Otis Worldwide Corp
Roper Technologies Inc
West Pharmaceutical Services, Inc.
Bancfirst Corp.
Albemarle Corp.
Aptargroup Inc.
WebdriverManager
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/471177.html
