Selenium ChromeDriver "get" doesn't reliably load @import fonts

Viewed 520

I have a few HTML pages like this:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic); 
body { font-family: 'Droid Serif'; }</style>
</head>
...

When loading the page with Selenium:

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--kiosk-printing')
browser = webdriver.Chrome(r"chromedriver.exe", options=chrome_options)
browser.get("http://www.example.com/")

then:

  • 50% of the time, the font doesn't get loaded (the page is displayed with default serif font (Times New Roman probably))
  • 50% of the time, the font is loaded

How to make font loading more reliable with Selenium?

Even re-loading the page a second time with time.sleep(2); browser.get(...) didn't help 100% of the time.

1 Answers

I stumbled upoun this Web API (https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet).

Try this code:


from selenium import webdriver
import time

u = 'https://fonts.google.com/'
driver = webdriver.Chrome(executable_path=r"chromedriver.exe")
driver.maximize_window()
driver.get(u)

while True:
    script = '''return document.fonts.status;'''
    loaded = driver.execute_script(script)
    if loaded == 'loaded':
        print('All fonts loaded')
        break
    print('Fonts still loading')
    time.sleep(.5)

Must say that, in my case, chrome return the control to selenium only when the page is fully loaded (including fonts). Maybe you could provide a minimum example to test your 50-50 scenario

Related