This post will be quick beginner's tutorial for Selenium using Python binding. First step is to install "python-selenium" and get the required browser driver's. The official link has all the details required to install selenium package for python and links for getting drivers for different browsers.
First step is to import the webdriver class from selenium and set the path for the browser driver.
from selenium import webdriver
CHROME_DRIVER = r"./browser_drivers/chromedriver"
SAFARI_DRIVER = r"/usr/bin/safaridriver"
In this tutorial, I am using both Chrome and Safari brower. If you are using Mac, you would need additional settings.
Run the following command on Mac, if you get the not verified error :-
xattr -d com.apple.quarantine ./browser_drivers/chromedriver
Next, we will create the driver object to interact with the browser. Ths can be created by calling the appropritate browser class like Chrome, Firefox etc.
Note : For Mac, safaridriver is available by default and does not require any explicit download. Default location is /usr/bin/safaridriver and you might have to run this command once "safaridriver --enable"
driver = webdriver.Chrome(executable_path=CHROME_DRIVER)
#driver = webdriver.Safari(executable_path=SAFARI_DRIVER)
Once the driver object is created, we can interact with the browser and perform operations like opening a web page, getting the title and other details.
# Open the URL in the browser
driver.get("https://www.google.com")
# Get the title of the Page
print("Title of the webpage is {}".format(driver.title))
# Get the current URL of the page just visited
print("URL of the webpage is {}".format(driver.current_url))
# Go to another page
driver.get("https://wwww.yahoo.com")
# Refresh the web-page (Mimic the browser refresh button)
driver.refresh()
# Maximize the window
driver.maximize_window()
# Go back to previous page (Mimic the browser back button)
driver.back()
# Open a new tab and open a new website
current_tab_handle = driver.current_window_handle
print("Window handle for current tab is {}".format(current_tab_handle))
driver.execute_script("window.open('');")
#WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
new_tab_window = [x for x in driver.window_handles if x != current_tab_handle][0]
driver.switch_to.window(new_tab_window)
driver.get("https://www.reddit.com")
print("Window handle for new tab is {}".format(new_tab_window))
print("Title of the webpage is {}".format(driver.title))
# Close the browser
# Note : driver.close() will close only current tab in focus
driver.quit()
Comments
Post a Comment