【问题标题】:Web scraping image inside canvas画布内的网络抓取图像
【发布时间】:2017-11-13 02:44:09
【问题描述】:

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

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

我有什么方法可以通过网络抓取相同的图像来保存我可以通过浏览器手动保存的图像?

【问题讨论】:

    标签: python image canvas web-scraping beautifulsoup


    【解决方案1】:

    如果您使用 Selenium 进行网页抓取,您可以使用以下代码 sn-p 获取 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)
    

    【讨论】:

    • 谢谢,但我真的很难理解我应该在哪里修改我的详细信息。在哪里输入图像所在的标签名称?我设法用 Selenium 打开页面,但不确定如何使用您的代码 -- WebDriverException: Message: unknown error: Cannot read property 'toDataURL' of null --
    • 它确实有效,只是如果我在启动您的代码的同时启动登录页面的代码,您的代码在页面打开之前执行得太快。有“睡眠”命令吗?还有一个问题是我有很多标签“inlinesparkline canvas”,在这种情况下它不起作用
    • 它只保存第一个画布而不保存其他画布
    • 我尝试使用 'document.querySelectorAll' 但它说不是函数
    • 用这个排序:for i in range(0,3): base64_image = browser.execute_script("var i = {a}; return document.querySelectorAll('.inlinesparkline canvas')[i] .toDataURL('image/png').substring(21);".format(a=i)) # 解码base64图片 output_image = base64.b64decode(base64_image) # 保存到输出图片 open("image{a }.png".format(a=i), 'wb') as f: f.write(output_image)
    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多