簡體   English   中英

使用 Selenium 和 Google Maps API 的屏幕截圖地圖

[英]Screenshot Map using Selenium and Google Maps API

我正在嘗試使用 Selenium、PhantomJS 和 GoogleMaps API 來自動截屏/保存地圖。 我請求的 url 是一個帶有 javascript 的本地 html 文件來生成地圖。 當我打開本地文件時,我可以查看地圖,但是,當我運行以下代碼並嘗試對地圖進行截圖時,只保存了一張空白圖片。

我已經探索了 Google Static Maps 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()

`

有人可以指出我正確的方向嗎?

您應該等待頁面加載所有 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM