Tclack88
Tclack88

Reputation: 21

Selenium doesn't load page when running chrome headless - python - alert or pop up error

(irrelevant background info: my laptop was stolen, I'm making this so if it were to ever happen again, I'd have a decent chance of recovering it)

THE PROBLEM:

So I'm trying to get a python script running which will (secretly) screenshot the current geolocation as per this website: https://gps-coordinates.org/my-location.php

It works great without the headless option, but with it, the location just isn't loading. My suspicion is headless mode doesn't allow popups or alerts properly and as such chrome is not able to "remember" my choice to always allow location.

I've looked at the source code and the location information comes up under the class "leaflet-popup-content"

WHAT I'VE TRIED:

I've already tried using the wait for element present

as below:

def waitForLoad(browser):
    try:
        WebDriverWait(browser, 10, ignored_exceptions=[
            NoSuchElementException, TimeoutException
        ]).until(EC.presence_of_element_located((By.CLASS_NAME,'leaflet-popup-content')))
    except TimeoutException:
        print("Error, timed out, trying again")
        browser.refresh()
        waitForLoad(browser)
        return

I've also tried this with the firefox driver (geckodriver), but it's not even working before headless is set

THE CODE:

import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-infobars")
browser=webdriver.Chrome('/home/tclack/bin/chromedriver',chrome_options=chrome_options)
# YMMV this is the chromedriver I use and the location

url = "https://gps-coordinates.org/my-location.php"

browser.get(url)

browser.save_screenshot('screenshot.png')
browser.close()
browser.quit()

Expected output is a .png file with the current location selected as you would see if you ran this but commented out the "--headless" line (line 6). (also assuming this website is "whitelisted" in terms of allowing location)

Upvotes: 1

Views: 1215

Answers (1)

Tclack88
Tclack88

Reputation: 21

Workout Around found

I've figured something out. It's actually a completely different angle than I was trying. So I was experimenting with virtualdisplay, an old solution before headless mode came about in selenium. I've found I can use pyvirtualdisplay and set visibility to 0 the code is the exact same but I sandwich it between these lines:

from pyvirtualdisplay import Display

display = Display(visible=0, size = [1000,1000])

display.start()

.

.

.

#blah blah blah, selenium code

.

.

.

display.stop()

Interesting stuff, I'm not quire sure how headless mode and virtual displays with visibility set to 0 differ, but at least it has the effect I was looking for

Upvotes: 1

Related Questions