Skip to content

Instantly share code, notes, and snippets.

@jftuga
Created May 24, 2021 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jftuga/cf03690dc8d1d41e4f389e5df89ad142 to your computer and use it in GitHub Desktop.
Save jftuga/cf03690dc8d1d41e4f389e5df89ad142 to your computer and use it in GitHub Desktop.
Read the Chrome URL address bar with Python and Selenium
r"""
address_bar.py
-John Taylor
May-24-2021
Read the URL from the Chrome address bar using two different methods
Tested with Python 3/9/5 on Windows 10 v1809
"""
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class AddressBar:
def __init__(self, start_url: str):
self.start_url = start_url
# start the chrome web browser
self.browser_init()
self.nav()
def __del__(self):
print("closing chrome webdriver")
try:
self.driver.close()
except:
pass
def browser_init(self) -> webdriver:
chdrv = "chromedriver.exe"
chrome_options = Options()
chrome_options.add_argument("ignore-certificate-error")
chrome_options.add_argument("ignore-ssl-errors")
caps = webdriver.DesiredCapabilities().CHROME
caps['acceptInsecureCerts'] = True
caps['acceptSslCerts'] = True
# self.driver has a data type of: webdriver
self.driver = webdriver.Chrome(chdrv, options=chrome_options, desired_capabilities=caps)
def nav(self):
self.driver.get(self.start_url)
time.sleep(2.5)
def get_bar(self) -> str:
url = self.driver.current_url
return url
def get_bar_with_js(self) -> str:
url = self.driver.execute_script("return window.location.href;")
return url
def main():
bar = AddressBar("https://www.example.com")
answer = ""
while answer != "q":
answer = input("press 'q' to quit: ")
if "q" == answer:
break
u1 = bar.get_bar()
u2 = bar.get_bar_with_js()
print(f" get_bar: {u1=}")
print(f"get_bar_with_js: {u2=}")
if "__main__" == __name__:
main()
# end of script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment