4

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.

Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

2

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

Mattia Galati
  • 2,415
  • 16
  • 22
  • This worked for me, but only after I commented out `options.add_argument('--headless')` in my script. It would seem (at least in my case) that Chrome only downloads web fonts if they're "truly" visible. – user7290573 Apr 06 '21 at 13:28