Your ultimate guide

Showing posts with label Python with Selenium. Show all posts
Showing posts with label Python with Selenium. Show all posts

Fix Browser Closes Automatically - Immediately after test without Calling Quit and Close()

To resolve issues with automatically closing browsers while using Selenium in Python, it is necessary to properly configure the Chrome WebDriver:

To configure Chrome WebDriver pre-requirements:
  1. Before running the script, make sure you have the required Python packages installed. You can install them using pip if you haven't already:
    • pip install selenium webdriver-manager
  2. These commands will install the 'selenium' package for Selenium WebDriver and the 'webdriver-manager' package for managing WebDriver executables like ChromDriver automatically.
  3. To install packages using pip within PyCharm, you can follow these steps:
    1. Open PyCharm: Launch Pycharm and open your Python project or create a new one.
    2. Open a Terminal: In PyCharm, you can access a terminal by clicking on "View" in the menu bar and selecting "Tool Windows" and then "Terminal".
    3. Run the pip Command: In the terminal, run the following command.
      • pip install webdriver-manager
    4. Wait for Installation: Pip will download and install the package and its dependencies.



Here's how you can fix this issue:
  1. Import the necessary modules
    • from selenium.webdriver.chrome.service import Service
    • from webdriver_manager.chrome import ChromeDriverManager
  2. Creates an instance of the 'ChromeOptions' class, which allows you to configure various options and preferences for the Chrome WebDriver.
    • options = webdriver.ChromeOptions()
  3. Add an experimental option to the 'ChromeOptions' object and pass the "detach" option, set to True, which allows the WebDriver to detach from the browser session after the WebDriver script has finished executing. This means that the browser window will remain open even after your script has completed its tasks.
    • options.add_experimental_option("detach", True)
  4. Create a WebDriver instance for Chrome with the specified options. It uses the ChromeDriverManager to automatically download and manage the Chrome WebDriver executable (chromedriver.exe) and set it up for use with Selenium. 
    • driver = webdriver.Chrome(options = options, service = Service(ChromeDirverManager().install()))
  5. With this configuration, you can now use the 'driver' object to interact with the Chrome browser, and the browser window will remain open even after your Selenium script has been completed.
  6. If you call the quit or close() function, then the browser will close.



Example Programs:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By

  3. from selenium.webdriver.chrome.service import Service
  4. from webdriver_manager.chrome import ChromeDriverManager

  5. options = webdriver.ChromeOptions()
  6. options.add_experimental_option("detach", True)
  7. driver = webdriver.Chrome(options=options, service=Service(ChromeDriverManager().install()))

  8. driver.get("https://example.com")


Handling Drop Down using Selenium with Python

Select Class:
  • If we want to work on the drop-down first we need to create object an instance of the 'Select' Class.
    • Syntax: object = Select(dropdown_element)
    • Example:
      1. dropdown = driver.find_element(By.ID, 'tcg')
      2. obj = Select(dropdown)
    • Example 2:
      1. obj = Select(driver.find_element(By.ID, 'tcg'))
  • Select class interacts with dropdown elements in web pages.
  • Select Class contain different functions by using that function we can handle the dropdown elements.
    • Select Class functions are:
    1. options 
      • Returns a list of all options to this select tag
    2. all_selected_options(self) 
      • Return a list of all selected options to this select tag
    3. first_selected_option(self) 
      • The first selected option in this select tag
    4. select_by_value(self, value: str)
      • Select all options that have a value matching the argument.
    5. select_by_index(self, index: int)
      • Select the option at the given index.
    6. select_by_visible_text(self, text: str)
      • Select all options that display text matching the argument.
    7. deselect_all(self)
      • Clear all selected entries. This is only valid when the SELECT supports multiple selections.
    8. deselect_by_value(self, value:str)
      • Deselect all options that have a value matching the argument.
    9. deselect_by_index(self, value: int)
      • Deselect the option at the given index.
    10. deselect_by_visible_text(self, text:str)
      • Deselect all options that display text matching the argument.
Note: The Select Class functions are designed specifically for dropdowns on a web page created using the select tag.



Let's explore each function in a Select class in detail. Refer to the image below for the source code and output of a dropdown.





options:
    options function allows you to retrieve all the available options within a dropdown element.

Here's how you can use the option method in the Select class:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element on the page.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'options' function to retrieve all the available options as a list of 'WebElement' objects:
    • all_options = select.options
  6. Now, all_options will contain a list of WebElement objects, each representing an option within the dropdown.
  7. You can then perform various operations on these options, such as selecting an option, getting the text or value of an option, etc.
  8. For example, to print the text of all options:
    • for option in all_options:
    •     print(option.text)



all_selected_options:
    This function is used to retrieve all the selected options from a multi-select dropdown or list on a web page.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the multi-select dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'all_selected_options' function to retrieve all the selected options as a list of 'WebElement' objects:
    • selected_options = select.all_selected_options
  6. Now, selected_options will contain a list of WebElement objects.
  7. You can then perform various operations on these options, such as unselecting the option, getting the text or value of an option, etc.
  8. For example, to print the text of all selected options:
    • for option in selected_options:
    •     print(option.text)



first_selected_option:
    The 'fist_selected_option' function is used to retrieve the first selected option from a dropdown or list. 

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'first_selected_option' function to retrieve the first selected option as a WebElement object:
    • first_option = select.first_selected_option
  6. You can then access the text or other attributes of the first selected option:
    • print(first_option.text)



select_by_value('option_value'):
    The 'select_by_value' method is used to select an element by specifying its 'value' attribute in the dropdown.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'select_by_value' function to select an option by specifying its 'value' attribute:
    • select.select_by_value('option_value')
deselect_by_value:
    This function is exactly the opposite of the 'select_by_value' function. This is used to deselect an element by specifying its 'value' attribute in the dropdown.
    So in the above example instead of giving 'select_by_value' if you give 'deselect_by_value' then that option will be deselected from the multi-select dropdown.



select_by_index:
    The 'select_by_index' method is used to select an option in the dropdown by specifying its index. The index is a zero-based integer that represents the position of the option in the dropdown list.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg') //replace with the actual ID of your dropdown element.
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Use the 'select_by_index' method to select an option by specifying its index.
    • select.select_by_index(3)
  6. Then use the 'select_by_index(3)' function will select the fourth option(since the index is zero-based) in the dropdown.
Similarly, we have the 'deselect_by_index' function to deselect an option by specifying its index.



select_by_visible_text:
    The 'select_by_visible_text' function is used to select an option from a dropdown by specifying its visible text (the text that is displayed to the user).

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'select_by_visible_text' function to select an option by specifying its visible text:
    • select.select_by_visible_text('option_text')
  6. Then it will select the option with the text "option_text" in the dropdown.

Similarly, we have a function to deselect the option in the dropdown by using visible text that is 'deselect_by_visible_text'.



deselect_all:
    The 'deselect_all' function is used to deselect all selected options in a multi-select dropdown.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the multi-select dropdown.
    • select = Select(dropdown)
  5. Then use the 'deselect_all' function to deselect all selected options in the dropdown:
    • select.deselect_all()
  6. After calling 'select.deselect_all()', all previously selected options in the multi-select dropdown will be deselected.


Get Size and Position of a Web Element



How to get a web element's height, width and position using Selenium with Python?
    To get the size and position of a web element using Selenium with Python we will use the 'rect' method. The output will be returned in the form of a Dictionary type.
 
Example:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By

  3. driver = webdriver.Chrome()
  4. driver.get("https://testingcolleges.blogspot.com/2023/08/alerts-demo-pages.html")
  5. element = driver.find_element(By.ID, 'alertbox')
  6. print(element.rect)
Output: {'height': 19, 'width': 57, 'x': 120, 'y': 444}

Selenium - Wait using Python

Selenium - Waits:
    waiting is a crucial concept when automating web interactions. It helps ensure that your script waits for certain conditions to be met before proceeding to the next steps. This is especially important because web elements might take varying amounts of time to load or change on a page.

There are two main types of waits in Selenium:
  1. Implicit wait
  2. Explicit wait
Implicit Wait:
    The implicit wait is a global setting that applies to all elements on the page. It tells the Selenium WebDriver to wait for a certain amount of time before throwing an exception if an element is not immediately available. You set the implicit wait time using the implicitly_wait() method.
  • Example:
    1. from selenium import webdriver
    2. from selenium.webdriver.common.by import By

    3. driver = webdriver.Chrome()
    4. driver.implicitly_wait(10)

    5. driver.get("https://www.google.com/")
    6. driver.find_element(By.NAME, "q").send_keys("testingcolleges")
    7. driver.find_element(By.NAME, "btnK").click()

Explicit Wait:
    An explicit wait makes Webdriver wait for specific conditions to be met for a particular element. To use Explicit Wait we need to import "from selenium.webdriver.support.wait import WebDriverWait".
    You can use the WebDriverWait class in combination with expected conditions from the expected_conditions module to achieve explicit wait. For that, we need to import "from selenium.webdriver.support import expected_conditions".
  • Example:
    1. from selenium import webdriver
    2. from selenium.webdriver.common.by import By
    3. from selenium.webdriver.support.wait import WebDriverWait
    4. from selenium.webdriver.support import expected_conditions as EC

    5. driver = webdriver.Chrome()
    6. wait = WebDriverWait(driver, timeout=10)

    7. driver.get("https://www.google.com/")
    8. driver.find_element(By.NAME, "q").send_keys("testingcolleges")
    9. wait.until(EC\
    10.         .element_to_be_clickable(driver.find_element(By.NAME, "btnK")))\
    11.         .click()
    In the above example, we will give timeout=10 and the excepted condition as element_to_be_clickable. That means the driver will wait up to 10 seconds until the given element to be clickable.

Depending on the scenario use different excepted condition functions.

Excepted conditions are;
Functions Description
alert_is_present() An expectation for checking if an alert is currently present and switching to it
all_of(*expected_conditions) An expectation that all of multiple expected conditions is true.
any_of(*expected_conditions) An expectation that any of multiple expected conditions is true.
element_attribute_to_include(locator, str], …) An expectation for checking if the given attribute is included in the specified element.
element_located_selection_state_to_be(…) An expectation to locate an element and check if the selection state specified is in that state.
element_located_to_be_selected(locator, str]) An expectation for the element to be located is selected.
element_selection_state_to_be(element, …) An expectation for checking if the given element is selected.
element_to_be_clickable(mark, Tuple[str, str]]) An Expectation for checking an element is visible and enabled such that you can click it.
element_to_be_selected(element) An expectation for checking the selection is selected.
frame_to_be_available_and_switch_to_it(…) An expectation for checking whether the given frame is available to switch to.
invisibility_of_element(element, Tuple[str, …) An Expectation for checking that an element is either invisible or not present on the DOM.
invisibility_of_element_located(locator, …) An Expectation for checking that an element is either invisible or not present on the DOM.
new_window_is_opened(current_handles) An expectation that a new window will be opened and have the number of windows handles increase.
none_of(*expected_conditions) An expectation that none of 1 or multiple expected conditions is true.
number_of_windows_to_be(num_windows) An expectation for the number of windows to be a certain value.
presence_of_all_elements_located(locator, str]) An expectation for checking that there is at least one element present on a web page.
presence_of_element_located(locator, str]) An expectation for checking that an element is present on the DOM of a page.
staleness_of(element) Wait until an element is no longer attached to the DOM.
text_to_be_present_in_element(locator, str], …) An expectation for checking if the given text is present in the specified element.
text_to_be_present_in_element_attribute(…) An expectation for checking if the given text is present in the element’s attribute.
text_to_be_present_in_element_value(locator, …) An expectation for checking if the given text is present in the element’s value.
title_contains(title) An expectation for checking that the title contains a case-sensitive substring.
title_is(title) An expectation for checking the title of a page.
url_changes(url) An expectation for checking the current url.
url_contains(url) An expectation for checking that the current url contains a case- sensitive substring.
url_matches(pattern) An expectation for checking the current url.
url_to_be(url) An expectation for checking the current url.
visibility_of(element) An expectation for checking that an element, known to be present on the DOM of a page, is visible.
visibility_of_all_elements_located(locator, str]) An expectation for checking that all elements are present on the DOM of a page and visible.
visibility_of_any_elements_located(locator, str]) An expectation for checking that there is at least one element visible on a web page.
visibility_of_element_located(locator, str]) An expectation for checking that an element is present on the DOM of a page and visible.




Can we use explicit wait without the expected_condition module?
    Yes, you can use explicit wait without the 'expected_conditions' module by creating custom conditions using 'WebDriverWait'     along with lambda functions. While 'expected_conditions' provides a convenient way to express common conditions, using custom conditions can give you more flexibility in waiting for specific elements or situations.

Here's how you can use explicit wait with a custom condition using a lambda function:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By
  3. from selenium.webdriver.support.wait import WebDriverWait

  4. driver = webdriver.Chrome()
  5. wait = WebDriverWait(driver, 10)

  6. # Define a custom condition using a lambda function
  7. custom_condition = lambda driver: driver.find_element(By.ID, "element_id").is_displayed()

  8. element = wait.until(custom_condition)
  9. # Now you can interact with the element once it's located and displayed
    In the above example, the custom condition is a lambda function that checks if the element with the specified ID is displayed. You can modify the lambda function to suit your specific waiting criteria.
    However, keep in mind that the expected_conditions module provides a range of pre-defined conditions that cover common use cases, such as element visibility, element presence, element clickability, and more. Using these conditions can often make your code more readable and maintainable. But if you have unique or complex waiting requirements, creating custom conditions using lambda functions is a viable option.

Selenium - Keyboard Action using Python



Keyboard Actions:
    Keyboard Actions is an exclusive feature of Selenium in Python, that allows pressing keys through the keyboard such as ctrl+p, shift+t, etc.,

    When we want to use Mouse or Keyboard actions we should create an ActionChains class object and import "from selenium.webdriver import ActionChains", "from selenium.webdriver import Keys"
  • Syntax:
    • from selenium.webdriver import ActionChains, Keys
    • #
    • action_obj = ActionChains(driver)
Method for ActionChains Class:
perform(): perform-function in the ActionChains is used to create a chain of actions or operations you want to perform and execute the action.

Keyboard Keys used to send in ActionChians Class:
DECIMAL, LEFT_SHIFT, ALT, CONTROL, SHIFT, HELP, ENTER, ARROW_LEFT, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, BACK_SPACE, CANCEL, CLEAR, COMMAND, DELETE, DIVIDE, END, EQUALS, ESCAPE, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, HOME, INSERT, LEFT, LEFT_ALT, LEFT_CONTROL, META, MULTIPLY, NULL, NUMPAD0, NUMPAD1, NUMPAD2, NUMPAD3, NUMPAD4, NUMPAD5, NUMPAD6, NUMPAD7, NUMPAD8, NUMPAD9, PAGE_UP, PAGE_DOWN, PAUSE, RETURN, RIGHT, SEMICOLON, SEPARATOR, SPACE, SUBTRACT, ADD, TAB, DOWN, UP.




send_keys(key_to_send): This function sends keyboard input to a webpage.
  • Syntax:
    • a = ActionChains(driver)
    • a.send_keys(Keys.PAGE_DOWN).perform()




key_down(value, element=None): This function presses a Key without releasing it. It should only be used with modifier keys such as CONTROL, ALT, and SHIFT.
  • Syntax:
    • a = ActionChains(driver)
    • a.key_down(Keys.SHIFT).send_keys("testing").perform()




key_up(value, element=None): This function releases a Key. It should only be used with modifier keys such as CONTROL, ALT, and SHIFT.
  • Syntax:
    • a = ActionChains(driver)
    • a.key_down(Keys.SHIFT).send_keys("testing").key_up(Keys.Shift).perform()




Keyboard actions can also be used in combination with Mouse actions.
  • Example: Mouse over to a element and then send the arrow_down key.
    •  a = ActionChains(driver)
    • element = driver.find_element(By.ID, "abc")
    • a.move_to_element(element).send_keys(Keys.ARROW_DOWN).perform()








Selenium - Mouse Actions using Python

Mouse and Keyboard Action:
    When we want to use Mouse or Keyboard actions we should create an "ActionChains" class object and we should import "from selenium.webdriver import ActionChains".
  • Syntax:
    • from selenium.webdriver import ActionChains
    • #
    •  action_obj = ActionChains(driver)

Method for ActionChains Class:
perform(): perform-function in the ActionChains is used to create a chain of actions or operations you want to perform.





move_to_element(element):  This function is used to Move the mouse point to an element.
  • Syntax:
    • a =  ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.move_to_element(element).perform()




double_click(element):  This function can perform a double-click on an element.
  • Syntax:
    • a = ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.double_click(element).perform()




context_click(element):  This function can perform a (Mouse)Right-Click operation on an element.
  • Syntax:
    • a = ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.context_click(element).perform()




click_and_hold(element): This function can perform hold down the left mouse button on an element.
  • Syntax:
    • a =  ActionChains(driver)
    • element = driver.find_element(By.ID, "123")
    • a.click_and_hold("element").peroform()




drag_and_drop(Source, Destination): This function 
  • Syntax:
    • a = ActionChains(driver)
    • source = driver.find_element(By.ID, "123")
    • destination = driver.find_element(By.ID, "ABC")
    • a.drag_and_drop(source, destination).perform()




Note: if the element = None, then it performs the action on the current mouse position.




Program:
  1. from selenium import webdriver
  2. from selenium.webdriver import ActionChains
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/2023/08/alert-demo-pages.html")

  6. action = ActionChains(driver)
  7. # Double-Click
  8. double = driver.find_element(By.ID, "doubleclick")
  9. action.move_to_element(double).double_click().perform()
  10. time.sleep(2)

  11. # Right-Click
  12. right = driver.find_element(By.ID, "rclick")
  13. action.context_click(right).perform()
  14. time.sleep(2)

  15. driver.close()
OUTPUT:
    


Handling Drop downs using Selenium with Python


Handling drop-down:
 The Select class in selenium is used to handle the drop-down. The drop-down is created in an HTML document using the <select> tag.
    

    In order to utilize the Select class methods, we need to import "selenium.webdriver.support.select.Select" in our code.

The selenium Select class contains the following sub-functions:
  • options: This function gets the all options in the dropdown in a list of web elements.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • all_options = dropdown.options

      • print(len(all_options))

      • for option in all_options:
      •       option.click()

      • all_options[2].click()
  • select_by_visible_text("VisibleText"): This function selects the options based on the visible text in the drop-down.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • dropdown.select_by_visible_text("India")
  • select_by_value("value"): This function selects the option based on the value attribute.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • dropdown.select_by_value("ind")
  • select_by_index(index): To select an option, use the index number. Keep in mind that the index starts from zero, so to select the first option, use 0 as the index. For the second option, use 1 as the index, and so on. By using the correct index, you can easily select the desired option.
    • Syntax:
      • dropdown = Select(driver.find_element(By.ID, "tcg"))
      • dropdown.select_by_index(4)
Similarly, there are functions to deselect the selected option:
  • deselect_all()
  • deselect_by_visible_text("visibletext")
  • deselect_by_value("value")
  • deselect_by_index(index)



is_multiple: we can use this function to ensure whether the specified dropdown is a multi-select option dropdown or not. This method returns True when the corresponding dropdown is multi-select.
  • Syntax:
    • dropdown = Select(driver.find_element(By.ID, "tcg"))
    • multidrp = dropdown.is_multiple
    • if multidrp:
    •       print("The Dropdown is Multi-Select")
    • else:
    •       print("The Dropdown is not Multi-Select")

Handling Alerts using Selenium with Python

Alert in Selenium: An alert in Selenium is a small message box that appears on the screen to give the user some information or notification.







    With the assistance of Selenium, we can execute various tasks within an alert box such as accepting or dismissing it, obtaining alert messages, and sending actions. These actions rely on the use of the class selenium.webdriver.common.alert.Alert(driver).

Selenium alert methods:
  • accept() - This method accepts an alert pop-up.
    • Syntax:
      • alert = Alert(driver)
      • alert.accept()
  • dismiss() - This method dismisses an alert pop-up.
    • Syntax:
      • alert = Alert(driver)
      • alert.dismiss()
  • send_keys() - Send keys to alert
    • Syntax:
      • alert = Alert(driver)
      • alert.send_keys("Testing Colleges")
  • text - This method gets the alert message.
    • Syntax:
      • alert = Alert(driver)
      • message = alert.text
      • print(message)

Program:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.alert import Alert
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/2023/08/alerts-demo-pages.html")
  6. # Confirm Alert box
  7. altbox = driver.find_element(By.ID, "confirmbox")
  8. altbox.click()
  9. time.sleep(2)

  10. alert = Alert(driver)
  11. # print the alert message
  12. print(alert.text)
  13. # accept the alert box
  14. time.sleep(2)
  15. # close the window
  16. driver.close()

OUTPUT:
    













Handling Browser Windows using Python with Selenium


Handling Browser Windows:
  • With the use of Selenium, it is possible to switch between different Tabs(Windows) in a browser and carry out actions on each page.
  • Each browser window is assigned a unique address(Window name) that changes dynamically when the browser is opened.
  • It is through these addresses only we are able to switch to and perform actions on different tabs.
How do we switch windows/tabs?
    By using the "switch_to.window()" function we do switch to different windows/tabs.
    Syntax: driver.switch_to.window(window name)

How to get the window names?
 In Selenium we have two different methods to get the addresses of windows.
    1. current_window_handle
    2. window_handles

current_window_handle: By using this function we can get the only address of the parent window(first window).
    Syntax: driver.current_window_handle
    Example:
  1. parent_window = driver.current_window_handle
  2. # print parent window address
  3. print(parent_window)
  4. # Switch to the parent window
  5. driver.switch_to.window(parent_window)
window_handles: By using this function we can get All the windows addresses in a list. To access values in lists use the square brackets[ ] with the index.
    Syntax: driver.window_handles
    Example:
  1. windows = driver.window_handles
  2. # print the All windows addresses
  3. print(windows)
  4. # Switch to 1st window
  5. driver.switch_to.window(window[0]) 


Example program:
  1. import time
  2. from selenium import webdriver
  3. from selenium.webdriver.common.by import By

  4. driver = webdriver.Chrome()
  5. driver.get("https://testingcolleges.blogspot.com/p/windowhandlingdemo1.html")
  6. newTab = driver.find_element(By.XPATH, "//*[contains(@value, 'New Tab')]")
  7. newTab.click() 
  8. windows = driver.window_handles
  9. # print all windows Addresses
  10. print("All windows IDs: ", windows)
  11. # switch to 1st window
  12. driver.switch_to.window(windows[0])
  13. time.sleep(2)
  14. #switch to 2nd window
  15. driver.switch_to.window(windows[1])
  16. time.sleep(2)
  17. driver.quite()
OUTPUT: