selenium cannot screenshot a web element

前端 未结 2 1436
余生分开走
余生分开走 2021-01-16 02:14

I can screenshot a whole page using Firefox.get_screenshot_as_file(\'2.png\'),but when I screenshot a web element using passage.screenshot(\'1.png\'),it alway raise

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 02:54

    The screenshot of a web element is not implemented in the Firefox driver. A workaround would be to crop the targeted element from the screenshot:

    import StringIO
    from selenium import webdriver
    from PIL import Image
    
    driver = webdriver.Firefox()
    driver.get('http://stackoverflow.com')
    
    # get the logo element
    element = driver.find_element_by_id('hlogo')
    
    # crop to the logo from the screenshot
    rect = element.rect
    points = [rect['x'], rect['y'], rect['x'] + rect['width'], rect['y'] + rect['height']]
    with Image.open(StringIO.StringIO(driver.get_screenshot_as_png())) as img :
        with img.crop(points) as imgsub :
            imgsub.save("c:\\temp\\logo.png", 'PNG')
    

提交回复
热议问题