python - Canvas 内的网络抓取图像

标签 python image canvas web-scraping beautifulsoup

我正在网络抓取一个页面,其中显示了各种数字以及小价格图表的图像。

如果我在浏览器中单击此图像,我可以将该图表另存为 .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/

相关文章:

reactjs - 如何将 SVG 导入到 React 中基于类的子组件?

javascript - 使用 for 循环动态创建在 Canvas 中绘制的图像

javascript - Canvas DataURL 到带有 filePath 的图像

javascript - 将 RGB 一种颜色转换为图像 HTML 5 Canvas 的另一种颜色

python - 将字符串转换为日期不起作用

python - 如何编写 lambda 处理程序以将数据发送到 Elasticsearch

java - 最佳实践问题 : How to save a collection of images and a java object in a single file? 读取文件以进行呈现

Python Pandas : Apply method to column if condition met in another column

python - 带有 postgres 的游标,数据存储在哪里以及对数据库的调用次数

Java:在 Graphics 中使用 setClip 会更有效率吗?