如何获取给定URL的全屏截图?

时间:2019-05-31 15:03:41

标签: python selenium web-scraping selenium-chromedriver screenshot

我想拍摄整个网站的屏幕快照(不仅仅是打开浏览器时浏览器中的可见部分)。我搜索了解决方案,发现了很多答案,但似乎没有一个适合我。

我当前的方法适用于某些网站:

from selenium import webdriver
import time

def createPNGChrome(url):
    DRIVER = '/Users/userName/PycharmProjects/WebsiteMonitor/Screenshots/chromedriver'
    driver = webdriver.Chrome(DRIVER)

    driver.get(url)
    time.sleep(1.5)
    element = driver.find_element_by_tag_name('body')

    screenshot = element.screenshot_as_png
    driver.quit()

    return screenshot

# works
#fullPageScreenshot = createPNGChrome('https://news.ycombinator.com/')

# works
#fullPageScreenshot = createPNGChrome('https://www.spotify.com/de/')

# fails
fullPageScreenshot = createPNGChrome('https://www.de.abbott/media-center/press-releases/05-10-2018.html')  # fails

with open('fullPageScreenshot.png', "wb") as file:
    file.write(fullPageScreenshot)

对于最后一个网站(abbott),我遇到以下异常:

selenium.common.exceptions.WebDriverException: Message: unknown error: unhandled inspector error: {"code":-32000,"message":"Cannot take screenshot with 0 height."}
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.5 x86_64)

这种方法是否可靠?只要结果是可靠的整页截图,我也可以使用完全不使用硒的完全不同的解决方案。

0 个答案:

没有答案