【问题标题】:Selenium not loading full dynamic html webpage despite waiting尽管等待,Selenium 仍无法加载完整的动态 html 网页
【发布时间】:2022-01-09 05:51:30
【问题描述】:

我正在尝试加载 youtube 频道的视频页面并对其进行解析以提取最近的视频信息。我想避免使用 API,因为它有每日使用配额。 我遇到的问题是 Selenium 在打印“driver.pagesource”时似乎没有加载网页的完整 html:

from bs4 import BeautifulSoup
from selenium.webdriver import Chrome
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options

driver = Chrome(executable_path='chromedriver')
driver.get('https://www.youtube.com/c/Oxylabs/videos')

# Agree to youtube cookie popup
try:
    consent = driver.find_element_by_xpath(
        "//*[contains(text(), 'I agree')]")
    consent.click()
except:
    pass

# Parse html
WebDriverWait(driver,100).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="show-more-button"]')))
print(driver.page_source)

如上所示,我已尝试实现 WebDriverWait。这会导致超时异常错误。但是,下面的 xpath(/html - 网页结尾)不会导致超时异常:

WebDriverWait(driver,100).until(EC.visibility_of_element_located((By.XPATH, '/html')))

-但这也不会加载完整的 html。 我也尝试实现 time.sleep(100) 而不是 WebDriverWait,但这也会导致 html 不完整。任何帮助将不胜感激。

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    你要找的元素不在页面上,这是超时的原因:

    //*[@id="show-more-button"]
    

    您是否尝试过滚动到页面底部或寻找其他元素?

    driver.execute_script("arguments[0].scrollIntoView();", element)
    

    【讨论】:

    • 也许:elem = driver.find_element_by_xpath(//div[@id='contents'])
    • 然后是 elem.get_attribute("innerHTML")
    • 谢谢。使用 get_attribute("innerHTML") 而不是 driver.page_source 修复了另一个问题。
    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2012-07-05
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 2013-12-05
    相关资源
    最近更新 更多