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


问题内容

我正在使用硒刮擦无限滚动页面。

我正在尝试使用以下代码:

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

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

如何在python中使用Selenium
Webdriver滚动网页?

我将其更新为包括“ webdriver”而不是“ driver”,因为我将硒导入为webdriver。否则它将无法正常工作。

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

AttributeError: module 'selenium.webdriver' has no attribute 'execute_script'

我不太了解这意味着什么以及如何解决?我还没有找到有关此方面的信息。

我是python的新手,所以很可能缺少明显的东西,但是任何建议都将不胜感激。


问题答案:

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

因此,您必须使用实例来调用它,而不是调用webdriver.execute_script()(它会给您AttributeError),例如:browser.execute_script()