3
votes

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
Any luck with this? Disappointed to come across this a year later and see there are no answers. - user7290573
@user7290573 Feel free to start a 50 or 100-point bounty (I often do in such cases, it helps). - Basj

1 Answers

1
votes

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