创建一个滚动到页面底部的循环,然后检查该元素

发布时间 2023-09-09 16:37:18作者: 祺琪
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# create a dedicated wait object to wait for a brief period for the elements to be created.
wait = WebDriverWait(driver, 5)
# (...)
# find channel on SCROLLABLE side menu

# limit the number of scrolls
count = 0
while count < 5:
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
    try:
        channel_text = wait.until(
            EC.presence_of_element_located(
             (By.XPATH, f"//*[contains(text(), 'channel-name')]")
            )
        )
        break
    except TimeoutException:
        pass
    count += 1
else:
    # do whatever must be done if the element is never found.
    pass
print(channel_text)