我正在使用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
我从多个来源获得此代码,最新的是:
How can I scroll a web page using selenium webdriver in python?
我将其更新为包含“webdriver”而不是“driver”,因为我将selenium导入为webdriver。否则它不起作用。
我的问题是,当我运行代码时,我得到:
AttributeError: module 'selenium.webdriver' has no attribute 'execute_script'
我真的不明白这意味着什么以及如何解决它?我一直无法找到相关信息。
我是python的新手,所以我可能错过了一些明显的东西,但任何建议都会受到赞赏。
webdriver
是模块的名称,而不是您的实例。事实上,您使用以下行将您创建的实例分配给名称browser
:browser = webdriver.Chrome()
所以不要调用webdriver.execute_script()
(它会给你一个AttributeError
),你必须使用你的实例调用它,如:browser.execute_script()
。
为了使它工作,你必须创建一个webdriver实例,例如:
from selenium import webdriver
driver = webdriver.Chrome() # webdriver.Ie(), webdriver.Firefox()...
last_height = driver.execute_script("return document.body.scrollHeight")
您可以从here下载Chromedriver
您还需要add path to Chromedriver to your environment variable PATH或将下载的文件放入与Python可执行文件相同的文件夹中...
AttributeError: module 'selenium.webdriver' has no attribute 'execute_script'
您收到此错误是因为'execute_script'不是类属性,您不能直接使用它。由于它是一个实例属性,因此您应该创建该类的实例。请查看here以了解有关课程的更多信息。
由于'execute_script'作为实例属性运行,因此现在可以正常工作。
last_height = browser.execute_script("return document.body.scrollHeight")
你的最终代码看起来像这样:
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 = browser.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