【问题标题】:Screenshot Map using Selenium and Google Maps API使用 Selenium 和 Google Maps API 的截图地图
【发布时间】:2018-05-30 04:59:49
【问题描述】:

我正在尝试使用 Selenium、PhantomJS 和 GoogleMaps API 来自动截取/保存地图。我请求的 url 是一个本地 html 文件,带有 javascript 来生成地图。当我打开本地文件时,我可以查看地图,但是,当我运行以下代码并尝试截取地图时,只保存了一张空白图片。

我探索了 Google 静态地图 API,但我的地图有数百个标记,超出了 URL 长度限制。我正在尝试截取数百张会随着时间而变化并且需要设定大小的地图。我相信这是最好的方法。

作为参考,这里有一些测试 html 会显示 Google API 地图(注意:需要 API 密钥):https://developers.google.com/maps/documentation/javascript/earthquakes

这是我的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def maps():
    driver = webdriver.PhantomJS()
    driver.set_window_size(640,640)
    driver.implicitly_wait(5)
    driver.get("file:///U:/ABC%20Comps/test.html")    
    element = driver.find_element_by_id('map')
    driver.save_screenshot('test.png')
    driver.quit()

`

有人能指出正确的方向吗?

【问题讨论】:

标签: python selenium google-api phantomjs screenshot


【解决方案1】:

您应该等待页面加载所有 AJAX 请求并呈现它们。

Selenium 的正常工作流程是等待所有正常请求完成,然后转到下一行。但在某些情况下,由于异步请求等原因,事情并非如此。

下面,我将展示一个工作示例。它的作用是,它强制脚本等待请求数量停止变大,然后再等待 5 秒(以获得更好的渲染效果),然后截取屏幕截图。在这里,玩得开心! :

if platform.system() == 'Windows' :
        executables_extension='.exe'
    else :
        executables_extension=''

    options = FirefoxOptions()
    options.add_argument("--headless")
    browser = webdriver.Firefox(options=options, executable_path=os.path.dirname(os.path.realpath(__file__))+os.path.sep+'geckodriver'+executables_extension)
    requests = 0
    requests_stop = False
    browser.get(Extracted_URL)
    while requests_stop == False :
        requests_old = requests
        time.sleep(3)
        requests = browser.execute_script("var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network.length;")
        if requests_old == requests :
            time.sleep(5)
            requests = browser.execute_script("var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network.length;")
            if requests_old == requests :
                requests_stop = True

    browser.save_screenshot('screenie.png')
    time.sleep(1)
    browser.quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多