我的代码的一部分是创建一个函数来滚动页面,这是从抓取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
}""")
2条答案
按热度按时间s1ag04yj1#
当使用Selenium进行网页抓取时,最好等待元素显式加载。在您的情况下,很可能是您的驱动程序在页面完全加载之前执行了javascript。
您可以使用
WebDriverWait
函数:qvsjd97n2#
@granitosaurus说了什么,但也忘记了if,使用可选的链式运算符(?)。不要忘记“return”(非常重要)