Selenium 错误信息“selenium.webdriver 没有属性执行脚本”

agr*_*a94 4 python selenium driver selenium-webdriver

我正在使用 selenium 来抓取无限滚动页面。

我正在尝试使用此代码:

import time
import pandas as np
import numpy as np

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

browser = webdriver.Chrome()
url = 'https://twitter.com/search?f=tweets&q=csubwaystats%20since%3A2018-05-28%20until%3A2018-08-28'

browser.get(url)
time.sleep(1)

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = webdriver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    webdriver.execute_script("window.scrollTo(0,document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = webdriver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height
Run Code Online (Sandbox Code Playgroud)

我从多个来源获得了这个代码,最近的是:

如何在 python 中使用 selenium webdriver 滚动网页?

我将其更新为包含“webdriver”而不是“driver”,因为我将 selenium 作为 webdriver 导入。否则它不起作用。

我的问题是,当我运行代码时,我得到:

AttributeError: module 'selenium.webdriver' has no attribute 'execute_script'
Run Code Online (Sandbox Code Playgroud)

我真的不明白这是什么意思以及如何解决它?我一直无法找到这方面的信息。

我是 python 的新手,所以可能遗漏了一些明显的东西,但任何建议都将不胜感激。

Cor*_*erg 8

webdriver是模块的名称,而不是它的实例。实际上,您browser使用以下行将创建的实例分配给名称:browser = webdriver.Chrome()

所以不是调用webdriver.execute_script()(这将给你一个AttributeError),您可以使用您的实例,这样必须调用它:browser.execute_script()