【问题标题】:Screenshots are taken when the webpages have yet fully loaded when using PhantomJS in python在 python 中使用 PhantomJS 时网页尚未完全加载时截取屏幕截图
【发布时间】:2019-10-05 10:59:58
【问题描述】:

在我绑定使用 PhantomJs 和 Python 获取屏幕截图时出现问题,我得到的一些图像没有完全加载。

我尝试使用driver.implicitly_wait(5) 解决它,但没有成功。

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get("https://world.taobao.com")
driver.save_screenshot('x.png')

有人知道吗?

【问题讨论】:

    标签: python selenium selenium-webdriver phantomjs


    【解决方案1】:

    usingdriver.implicitly_wait(5) 将对页面中存在的所有元素应用一次,最多持续 5 秒,如果元素需要更长时间,这将是不够的。请注意,它也只需要编写一次。 您可以使用 time 模块添加 time.sleep(10) 或类似的等待时间(如果您确定图像完全加载需要多长时间),或者使用显式等待。

    导入以下内容

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    

    假设您有要确保可见的元素的定位器,并希望在本示例中使用 XPath 来定位它(以防多个元素循环通过返回的元素)

    locator = (By.XPATH,"SOME_VALID_XPATH")
    

    定义一个变量来保存WebDriverWait 对象,如下所示:

    wait = WebDriverWait(driver, 10)
    wait.until(EC.visibility_of_element_located(locator))
    

    这个问题可能是图像可以有尺寸,因此被认为是已加载和可见的。一种解决方法是存储图像并断言加载的图像与它们相等,这将是一个简单案例的相当复杂的解决方案。

    我建议使用time 模块或显式等待。

    Link to the documentation

    【讨论】:

    • 谢谢,但这并不能解决 PhantomJS 案例中的问题,我找到了一种通过执行 JS 脚本滚动整个页面来处理它的方法,它发布在下面。
    • 很高兴你找到了它,但是一次滚动页面 n 个像素只是在你截屏之前增加了延迟。 PhantomJS 只是另一个 Web 驱动程序,如果等待到位,将获取已完成的屏幕。
    【解决方案2】:

    我发现解决这个问题的方法是执行一个JS脚本来滚动整个页面:

    from selenium import webdriver
    import time
    
    
    def take_screenshot(url, save_fn="capture.png"):
        browser = webdriver.Chrome()
        # browser = webdriver.PhantomJS()
        browser.set_window_size(1200, 900)
        browser.get(url)
        # scroll down to the bottom and scroll back to the top
        browser.execute_script("""
            (function () {
                var y = 0;
                var step = 100;
                window.scroll(0, 0);
    
                function f() {
                    if (y < document.body.scrollHeight) {
                        y += step;
                        window.scroll(0, y);
                        setTimeout(f, 100);
                    } else {
                        window.scroll(0, 0);
                        document.title += "scroll-done";
                    }
                }
    
                setTimeout(f, 1000);
            })();
        """)
    
        for i in range(30):
            if "scroll-done" in browser.title:
                break
            time.sleep(10)
            print(i)
    
        browser.save_screenshot(save_fn)
        browser.close()
    
    
    if __name__ == "__main__":
    
        take_screenshot("http://world.taobao.com")
    

    感谢这篇原帖:https://cloud.tencent.com/developer/article/1406656

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-22
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 2017-04-04
      • 1970-01-01
      相关资源
      最近更新 更多