jquery 无法使用Selenium Webdriver读取null的属性(阅读“scrollHeight”)

q3qa4bjr  于 2023-02-15  发布在  jQuery
关注(0)|答案(2)|浏览(212)

我的代码的一部分是创建一个函数来滚动页面,这是从抓取GoogleJobs here的代码复制而来的
它会抛出错误“javascript错误:无法读取null的属性(阅读“scrollHeight”)”
我不确定为什么document.querySelector('.zxU94d')为空

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

def scroll_page(url):
    service = Service(ChromeDriverManager().install())
    
    # Add the settings to run the Chrome browser 
    options = webdriver.ChromeOptions()
    options.add_argument("--headless")
    options.add_argument('--lang=en')
    options.add_argument("user-agent=AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36")

    driver = webdriver.Chrome(service=service, options=options)
    
    driver.get(url)
    
    # Store the initial height of Google Jobs page
    old_height = driver.execute_script("document.querySelector('.zxU94d').scrollHeight")

当我转到手动访问的URL(here)时,我可以毫无问题地在Console上获得高度。
如果我尝试处理null,它将返回NoneType

old_height = driver.execute_script("""if (document.querySelector('.zxU94d')) {
                                           document.querySelector('.zxU94d').scrollHeight
                                       }""")
s1ag04yj

s1ag04yj1#

当使用Selenium进行网页抓取时,最好等待元素显式加载。在您的情况下,很可能是您的驱动程序在页面完全加载之前执行了javascript。
您可以使用WebDriverWait函数:

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

_timeout = 10  # seconds
WebDriverWait(driver, _timeout).until(
    expected_conditions.presence_of_element_located(
        (By.CSS_SELECTOR, ".zxU94d")
    )
)
old_height = driver.execute_script("""if (document.querySelector('.zxU94d')) {
                                           document.querySelector('.zxU94d').scrollHeight
                                       }""")
qvsjd97n

qvsjd97n2#

@granitosaurus说了什么,但也忘记了if,使用可选的链式运算符(?)。不要忘记“return”(非常重要)

old_height = driver.execute_script("""     
  return document.querySelector('.zxU94d')?.scrollHeight || 0
""")

相关问题