【问题标题】:Python Selenium webdriver: Does not scroll down the page if browser is minimisedPython Selenium webdriver:如果浏览器最小化,则不会向下滚动页面
【发布时间】:2021-05-11 19:47:59
【问题描述】:

我使用 Python Selenium Webdriver 编写了一个脚本,用于从 google play 商店中抓取应用审阅者。我编写了一个脚本,它向下滚动用户评论者的页面并点击“显示更多评论”按钮 5 次。 5 次后,它会检查最后审查日期是否小于给定日期,然后停止滚动,否则继续滚动。代码如下:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import datetime as dt
from datetime import datetime

driver = webdriver.Chrome()
baseurl = 'https://play.google.com/store/apps/details?id=com.mapmyrun.android2&showAllReviews=true'
driver.get(baseurl)

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[./span[text()='Most relevant']]"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[@role='option'][./span[text()='Newest']]"))).click() 

counter = 0
while True:
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
    time.sleep(2)
    counter = counter + 1
    if len(driver.find_elements_by_xpath("//span[text()='Show More']"))>0:
        driver.find_element_by_xpath("//span[contains(text(),'Show More')]").click()
        counter = 0
    if counter == 10:
        
        person_info = driver.find_elements_by_xpath("//div[@class='d15Mdf bAhLNe']")
        last_date = person_info[-1].find_element_by_xpath(".//span[@class='p2TkOb']").text
        print(datetime.strptime(last_date,"%B %d, %Y").strftime("%Y/%m/%d"))
        if datetime.strptime(last_date,"%B %d, %Y").strftime("%Y/%m/%d") < dt.datetime(year=2020,month=12,day=2).strftime("%Y/%m/%d"):
            break;
        
        else:
            counter = 0


   print(counter)
        

现在,如果 Chrome 窗口在屏幕上保持活动状态,上述代码可以正常工作。但是,如果我最小化 chrome 浏览器,它会一次又一次地显示相同的旧日期。例如,当脚本开始运行时,我最小化了 chrome 浏览器,在计数为 5 之后,它显示日期 2021/02/07。由于日期大于 2020/12/2,循环将继续并重置计数器。但是,它第二次再次显示相同的日期(即 2021/02/07),它会不断重复,直到我再次最大化 chrome 浏览器。 selenium webdriver 中是否有任何方法可以使页面保持向下滚动,即使页面已最小化或处于非活动状态?

【问题讨论】:

  • 为什么你期望它会被最小化滚动?页面最小化后可以手动滚动吗?我猜你不能。如果您不需要显示浏览器,请使用无头模式。

标签: python python-3.x selenium selenium-webdriver


【解决方案1】:

selenium 是浏览器的遥控器,就像人类在使用浏览器一样。 selenium 所做的动作是为了尽可能地模仿人类的动作。例如 selenium 拒绝单击页面上存在但对人类不可见的按钮。当然,由于 selenium 是一个程序而不是人类,它只能估计人类可能采取的行动,有时会犯错误。

在您的情况下:如果您将浏览器最小化,则几乎不可能进行任何人工操作。你得到的结果基本上是硒的错误。理想情况下,您应该收到一条错误消息,说明如果浏览器最小化,则无法执行任何操作。所以你得到的结果是一个错误的副作用,恰好导致旧日期。

解决您的问题的方法很简单:既然您不想看到浏览器,您应该使用无头模式。无头模式意味着浏览器已打开但未绘制到屏幕上。它仍然被吸引到一些隐藏的缓冲区。所以网站(和硒)认为浏览器是正常打开的(没有最小化)。但对使用计算机的人来说是不可见的。

代码看起来像这样:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.headless = True
driver = webdriver.Chrome(options=chrome_options)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2012-08-30
    相关资源
    最近更新 更多