simonw / shot-scraper

A command-line utility for taking automated screenshots of websites
https://shot-scraper.datasette.io
Apache License 2.0
1.57k stars 70 forks source link

It would be great to have an `omit_background` option so you can take transparent PNG screenshots #108

Closed palewire closed 1 year ago

palewire commented 1 year ago

It's in the options, but I don't think it's available.

https://playwright.dev/python/docs/api/class-locator#locator-screenshot-option-omit-background

simonw commented 1 year ago

Seeing an error with this in CI: https://github.com/simonw/shot-scraper/actions/runs/4815473826/jobs/8574190652

Screenshot of '.day' on 'https://simonwillison.net/' written to 'examples/selector-all.png'
Screenshot of 'https://simonwillison.net/' written to 'examples/simon-narrow.png'
Error: TypeError: Cannot set properties of undefined (setting 'backgroundColor')
    at eval (eval at evaluate (:195:30), <anonymous>:1:60)
    at eval (<anonymous>)
    at UtilityScript.evaluate (<anonymous>:195:30)
    at UtilityScript.<anonymous> (<anonymous>:1:44)
simonw commented 1 year ago

Looks like the error is from: https://github.com/simonw/shot-scraper/blob/ebc2e909821f926979550bb6e1295b59b7a93da0/tests/run_examples.sh#L33-L37

That gives me the same error locally too:

% shot-scraper https://simonwillison.net/ \
  -h 800 -o examples/simonwillison-transparent.png \
  --javascript "document.getElementsByTagName('body').style.backgroundColor='transparent'" \
  --omit-background
Error: TypeError: Cannot set properties of undefined (setting 'backgroundColor')
    at eval (eval at evaluate (:197:30), <anonymous>:1:60)
    at eval (<anonymous>)
    at UtilityScript.evaluate (<anonymous>:197:30)
    at UtilityScript.<anonymous> (<anonymous>:1:44)
simonw commented 1 year ago

It's because document.getElementsByTagName('body') returns an array-like collection. I'm going to try document.querySelector('body') instead.

simonw commented 1 year ago

This worked without an error:

shot-scraper https://simonwillison.net/ \
  -h 800 -o examples/simonwillison-transparent.png \
  --javascript "document.querySelector('body').style.backgroundColor='transparent'" \
  --omit-background

And produced this image (which has a transparent background, though you can't see that on GitHub Issues because the background here is white too):

simonwillison-transparent