我正在网络抓取一个页面,其中显示了各种数字以及小价格图表的图像。
如果我在浏览器中单击此图像,我可以将该图表另存为 .png
图像。
当我查看源代码时,该元素在检查时看起来像这样:
<div class="performance_2d_sparkline graph ng-isolate-scope ng-scope" x-data-percent-change-day="ticker.pct_chge_1D" x-sparkline="watchlistData.sparklineData[ticker.ticker]">
<span class="inlinesparkline ng-binding">
<canvas width="100" height="40" style="display: inline-block; width: 100px; height: 40px; vertical-align: top;">
</canvas>
</span>
</div>
有什么方法可以通过网络抓取来保存我可以通过浏览器手动保存的相同图像吗?
最佳答案
如果您使用 Selenium 进行网页抓取,则可以使用以下代码片段获取 Canvas 元素并将其保存到图像文件中:
# get the base64 representation of the canvas image (the part substring(21) is for removing the padding "data:image/png;base64")
base64_image = driver.execute_script("return document.querySelector('.inlinesparkline canvas').toDataURL('image/png').substring(21);")
# decode the base64 image
output_image = base64.b64decode(base64_image)
# save to the output image
with open("image.png", 'wb') as f:
f.write(output_image)
关于python - Canvas 内的网络抓取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44485616/