mysocial
Connect with friends and the world around you on MySocial.
Create a Page for a celebrity, brand or business.
Online Learning Platform
Connect with friends and the world around you on MySocial.
Create a Page for a celebrity, brand or business.
Below is a table that demonstrates the conversion of various Python data types into other data types. Each entry in the table includes the original data type, the target data type, a code snippet to perform the conversion, and an example output.
| Data Type | Target Data Type | Code | Output |
int | float | num_int = 10 num_float = float(num_int) | 10.0 |
int | str | num_int = 42 num_str = str(num_int) | ’42’ |
int | complex | num_int = 5 num_complex = complex(num_int) | (5+0j) |
int | list | num_int = 123 num_list = list(num_int) | TypeError: ‘int’ object is not iterable Conversion is not possible |
int | dict | num_int = 1 num_dict = dict(num_int) | TypeError: ‘int’ object is not iterable Conversion is not possible |
int | tuple | num_int = 7 num_tuple = tuple(num_int) | TypeError: ‘int’ object is not iterable Conversion is not possible |
| int | bool | num_int = 0 num_bool = bool(num_int) print(num_bool) num_int1 = 123 num_bool1 = bool(num_int1) print(num_bool1) | False True |
| Data Type | Target Data Type | Code | Output |
| float | int | num_float = 10.5 num_int = int(num_float) | 10 |
| float | str | num_float = 3.14 num_str = str(num_float) | ‘3.14’ |
| float | complex | num_float = 3.0 num_complex = complex(num_float,4.5) | (3+4.5j) |
| float | list | num_float = 3.14 num_list = list(num_float) | TypeError: ‘int’ object is not iterable Conversion is not possible |
| float | dict | num_float = 2.5 num_dict = dict(num_float) | TypeError: ‘int’ object is not iterable Conversion is not possible |
| float | tuple | num_float = 1.5 num_tuple = float(num_float) | TypeError: ‘int’ object is not iterable Conversion is not possible |
| float | bool | num_int = 0 num_bool = bool(num_int) print(num_bool) num_int1 = 12.3 num_bool1 = bool(num_int1) print(num_bool1) | False True |
| Data Type | Target Data Type | Code | Output |
| complex | int | num_complex = complex(3, 4) num_int = int(num_complex) | TypeError: int() argument must be a string, a bytes-like object or a real number, not ‘complex’ Conversion is not possible. |
| complex | float | i). num_complex = complex(3, 4) num_float = float(num_complex) ii). num_complex = complex(3, 4) num_float = float(num_complex.real) | i).TypeError: float() argument must be a string or a real number, not ‘complex’ Conversion is not possible. ii). 3 |
| complex | str | num_complex = complex(1, 2)<br>num_str = str(num_complex) | ‘(1+2j)’ |
| complex | list | num_complex = complex(2, 3) num_list = [num_complex.real, num_complex.imag] | [2.0, 3.0] |
| complex | dict | num_complex = complex(2, 1) num_dict = {‘real’: num_complex.real, ‘imag’: num_complex.imag} | {‘real’: 2.0, ‘imag’: 1.0} |
| complex | tuple | num_complex = complex(4, 5) num_tuple = (num_complex.real, num_complex.imag) | (4.0, 5.0) |
| complex | bool | num_complex = complex(0, 0) num_bool = bool(num_complex) | False |
| Data Type | Target Data Type | Code | Output |
str | int | num_str = ‘987’ num_int = int(num_str) | 987 |
str | float | num_str = ‘2.71’ num_float = float(num_str) | 2.71 |
str | complex | num_str = ‘1+2j’ num_complex = complex(num_str) | (1+2j) |
str | list | str_val = ‘hello’ list_val = list(str_val) | [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] |
str | dict | str_val = ‘hello’ dict_val = {str_val: len(str_val)} | {‘hello’: 5} |
str | tuple | str_val = ‘abc’ tuple_val = tuple(str_val) | (‘a’, ‘b’, ‘c’) |
str | bool | str_val = ‘True’ bool_val = bool(str_val) | True |
| Data Type | Target Data Type | Code | Output |
| list | int | num_list = [1, 2, 3] num_int = int(”.join(map(str, num_list))) | 123 |
| list | float | num_list = [3, 1, 4] num_float = float(”.join(map(str, num_list))) | 314.0 |
| list | str | num_list = [10, 20, 30] num_str = ‘, ‘.join(map(str, num_list)) | ’10, 20, 30′ |
| list | complex | num_list = [2, 3] num_complex = complex(num_list[0], num_list[1]) | (2+3j) |
| list | dict | num_list = [1, 2] num_dict = dict(zip(num_list, [‘one’, ‘two’])) | {1: ‘one’, 2: ‘two’} |
| list | tuple | num_list = [7, 8, 9] num_tuple = tuple(num_list) | (7, 8, 9) |
| list | bool | num_list = [0, 1, 0] num_bool = any(num_list) | True |
| Data Type | Target Data Type | Code | Output |
| tuple | int | num_tuple = (4, 5, 6) num_int = int(”.join(map(str, num_tuple))) | 456 |
| tuple | float | num_tuple = (1, 2) num_float = float(‘.’.join(map(str, num_tuple))) | 1.2 |
| tuple | str | num_tuple = (7, 8, 9) num_str = ‘, ‘.join(map(str, num_tuple)) | ‘7, 8, 9’ |
| tuple | complex | num_tuple = (3, 4) num_complex = complex(num_tuple[0], num_tuple[1]) | (3+4j) |
| tuple | list | num_tuple = (10, 20) num_list = list(num_tuple) | [10, 20] |
| tuple | dict | num_tuple = (‘x’, 1) num_dict = dict([num_tuple]) | {‘x’: 1} |
| tuple | bool | num_tuple = (0, 0) num_bool = any(num_tuple) | False |
| Data Type | Target Data Type | Code | Output |
| ict | int | num_dict = {‘a’: 1} num_int = int(list(num_dict.keys())[0]) | 97 |
| dict | float | num_dict = {‘pi’: 3.14} num_float = float(list(num_dict.values())[0]) | 3.14 |
| dict | str | num_dict = {1: ‘one’} num_str = str(list(num_dict.keys())[0]) | ‘1’ |
| dict | complex | num_dict = {3: 5} num_complex = complex(list(num_dict.keys())[0], list(num_dict.values())[0]) | (3+5j) |
| dict | list | num_dict = {‘a’: 1, ‘b’: 2} num_list = list(num_dict.items()) | [(‘a’, 1), (‘b’, 2)] |
| dict | tuple | num_dict = {‘x’: 10, ‘y’: 20} num_tuple = tuple(num_dict.items()) | ((‘x’, 10), (‘y’, 20)) |
| dict | bool | num_dict = {‘flag’: True} num_bool = bool(list(num_dict.values())[0]) | True |
| Data Type | Target Data Type | Code | Output |
| set | int | num_set = {1, 2, 3} num_int = int(”.join(map(str, num_set))) | 123 |
| set | float | num_set = {3, 1, 4} num_float = float(”.join(map(str, num_set))) | 314.0 |
| set | str | num_set = {10, 20, 30} num_str = ‘, ‘.join(map(str, num_set)) | ’10, 20, 30′ |
| set | complex | num_set = {2, 3} num_complex = complex(list(num_set)[0], list(num_set)[1]) | (2+3j) |
| set | list | num_set = {1, 2, 3} num_list = list(num_set) | [1, 2, 3] |
| set | dict | num_set = {1, 2, 3} num_dict = dict.fromkeys(num_set, ‘value’) | {1: ‘value’, 2: ‘value’, 3: ‘value’} |
| set | tuple | num_set = {7, 8, 9) num_tuple = tuple(num_set) | (8, 9, 7) |
| set | bool | num_set = set() num_bool = bool(num_set) | False |
| Data Type | Target Data Type | Code | Output |
| bool | int | num_bool = False num_int = int(num_bool) | 0 |
| bool | float | num_bool = True num_float = float(num_bool) | 1.0 |
| bool | str | num_bool = True num_str = str(num_bool) | ‘True‘ |
| bool | complex | num_bool = True num_complex = complex(int(num_bool), 0) | (1+0j) |
| bool | list | num_bool = False num_list = [int(num_bool)] | [0] |
| bool | dict | num_bool = True num_dict = {str(num_bool): ‘boolean’} | {‘True’: ‘boolean’} |
| bool | tuple | num_bool = False num_tuple = (int(num_bool),) | (0,) |
When automating web applications with Python Selenium, handling keyboard interactions is crucial for testing scenarios like filling forms, simulating keypresses, and navigating applications. Selenium provides robust functionalities to simulate user interactions with a keyboard using the ActionChains class and send_keys method.
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains
The send_keys method allows us to send keyboard inputs to elements like text fields.
# Launch browser
driver = webdriver.Chrome()
driver.get("https://facebook.com")
# Locate the input field
input_field = driver.find_element("name", "username")
# Simulate typing
input_field.send_keys("TestUser")
Selenium provides the Keys class to simulate keyboard shortcuts like CTRL+C, CTRL+V, ENTER, and more.
input_field.send_keys(Keys.ENTER)
input_field.send_keys("Test")
input_field.send_keys(Keys.CONTROL, 'a') # Select all
input_field.send_keys(Keys.CONTROL, 'c') # Copy
input_field.send_keys(Keys.TAB) # Move to next field
input_field.send_keys(Keys.CONTROL, 'v') # Paste
ActionChains helps perform multiple actions, including pressing and releasing keys.
# Create ActionChains instance
actions = ActionChains(driver)
# Locate element
element = driver.find_element("id", "search")
# Perform actions
actions.click(element)
actions.send_keys("Selenium Automation")
actions.send_keys(Keys.RETURN)
actions.perform()
Some keys like BACKSPACE, DELETE, ESC, F1-F12, SHIFT, ALT, CONTROL are essential in automation.
input_field.send_keys(Keys.BACKSPACE) # Deletes last character input_field.send_keys(Keys.ESCAPE) # Simulates ESC key
Pressing and holding keys like SHIFT allows us to capitalize text or perform shortcuts.
actions.key_down(Keys.SHIFT).send_keys("selenium").key_up(Keys.SHIFT).perform()
Instead of sending keys directly, send_keys_to_element allows targeted input.
from selenium.webdriver.common.actions.action_builder import ActionBuilder action = ActionBuilder(driver) action.send_keys_to_element(input_field, "Automated Text").perform()
driver.get("https://facebook.com/login")
# Locate fields
username = driver.find_element("name", "username")
password = driver.find_element("name", "password")
# Type credentials
username.send_keys("testuser")
password.send_keys("securepassword")
password.send_keys(Keys.RETURN) # Press Enter
alert = driver.switch_to.alert actions.send_keys(Keys.ESCAPE).perform()
Chrome options in Python Selenium play a crucial role in configuring and customizing the Chrome browser for automation tasks. By utilizing ChromeOptions, testers and developers can enhance their browser automation scripts by enabling or disabling certain features, managing extensions, controlling headless browsing, and much more.
To begin using ChromeOptions, we must import the required modules and instantiate the WebDriver with custom options. Below is a basic implementation:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# Instantiate ChromeOptions
chrome_options = Options()
# Initialize WebDriver with options
driver = webdriver.Chrome(options=chrome_options)
This code initializes the Chrome browser with default settings. However, we can add multiple options to configure the browser according to our needs.
Headless mode runs Chrome without a visible UI, making tests faster and more efficient:
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
This is particularly useful for continuous integration (CI) pipelines where a graphical interface is unnecessary.
To prevent pop-up notifications from interrupting automation tests:
chrome_options.add_argument("--disable-notifications")
To launch Chrome in incognito mode for testing privacy-related functionalities:
chrome_options.add_argument("--incognito")
In some cases, GPU acceleration may cause issues. We can disable it as follows:
chrome_options.add_argument("--disable-gpu")
To start Chrome with a maximized window:
chrome_options.add_argument("--start-maximized")
To simulate different browsers and devices, we can set a custom User-Agent:
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
chrome_options.add_argument(f"--user-agent={user_agent}")
To route browser traffic through a proxy:
proxy = "http://your.proxy.server:port"
chrome_options.add_argument(f"--proxy-server={proxy}")
To launch Chrome without loading any installed extensions:
chrome_options.add_argument("--disable-extensions")
Chrome provides experimental options that can be enabled via ChromeOptions:
prefs = {"profile.default_content_setting_values.cookies": 2} # Block cookies
chrome_options.add_experimental_option("prefs", prefs)
To disable animations for improved performance:
chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
If Chrome is installed in a non-standard location:
chrome_options.binary_location = "/path/to/chrome"
For debugging JavaScript errors, we can enable logging:
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
capabilities = DesiredCapabilities.CHROME.copy()
capabilities["goog:loggingPrefs"] = {"browser": "ALL"}
driver = webdriver.Chrome(desired_capabilities=capabilities, options=chrome_options)
Here’s a complete example demonstrating multiple ChromeOptions:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920x1080")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument("--no-sandbox")
# Initialize WebDriver
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.facebook.com")
print(driver.title)
driver.quit()
While Selenium can execute scripts with a visible browser window, headless execution allows tests to run in the background, significantly improving performance and efficiency.
Headless mode is particularly useful for environments where GUI is not required, such as server-side automation, continuous integration (CI/CD) pipelines, and web scraping. This article provides a comprehensive guide on how to execute Selenium scripts in headless mode using Python.
There are several benefits to using headless mode in Selenium:
Before running Selenium in headless mode, ensure you have the following installed:
Google Chrome supports headless execution natively. Below is how you can configure Selenium with Chrome in headless mode:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# Set up Chrome options
chrome_options = Options()
chrome_options.add_argument("--headless") # Enable headless mode
chrome_options.add_argument("--disable-gpu") # Recommended for Windows OS
chrome_options.add_argument("--window-size=1920x1080") # Set window size
driver = webdriver.Chrome(options=chrome_options)
# Open a website
driver.get("https://www.facebook.com")
print(driver.title)
# Close the browser
driver.quit()
For Mozilla Firefox, you need to set the headless argument:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
# Set up Firefox options
firefox_options = Options()
firefox_options.add_argument("--headless")
driver = webdriver.Firefox(options=firefox_options)
# Open a website
driver.get("https://www.facebook.com")
print(driver.title)
# Close the browser
driver.quit()
Apart from Chrome and Firefox, Selenium also supports headless execution with other browsers like Edge and Opera. Here’s how you can configure them:
from selenium import webdriver
from selenium.webdriver.edge.options import Options
edge_options = Options()
edge_options.add_argument("--headless")
driver = webdriver.Edge(options=edge_options)
# Open a website
driver.get("https://www.facebook.com")
print(driver.title)
# Close the browser
driver.quit()
Even though the browser is running in headless mode, you can still capture screenshots:
driver.save_screenshot("screenshot.png")
When dealing with web pages, there are instances where elements are not immediately visible due to scrolling. In such cases, scrolling to a specific element ensures that Selenium can interact with it properly. This guide will cover the most effective techniques for scrolling to an element using Python Selenium.
One of the most reliable ways to scroll to an element in Selenium is by executing JavaScript commands. JavaScript’s scrollIntoView() method is effective for scrolling directly to an element.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a webpage
driver.get("https://facebook.com")
# Locate the element to scroll to
element = driver.find_element(By.ID, "target-element")
# Scroll to the element using JavaScript
driver.execute_script("arguments[0].scrollIntoView();", element)
# Pause for visibility
time.sleep(2)
# Close the driver
driver.quit()
ActionChains in Selenium provides a human-like scrolling experience, ensuring smooth interactions with dynamically loaded elements.
from selenium.webdriver.common.action_chains import ActionChains # Initialize ActionChains actions = ActionChains(driver) # Move to the element actions.move_to_element(element).perform()
Another JavaScript-based approach involves scrolling by a specific pixel value.
driver.execute_script("window.scrollBy(0, 500);")
To scroll to an exact position on a page, use window.scrollTo().
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
Some pages load elements dynamically, requiring additional wait time before interacting with elements. The best approach is to use WebDriverWait to ensure elements are visible before scrolling.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Wait until the element is present
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "target-element")))
# Scroll to the element
driver.execute_script("arguments[0].scrollIntoView();", element)
To ensure smooth scrolling in Selenium:
Selenium is one of the most powerful automation tools used for web scraping, browser automation, and testing. Often, there are cases where interacting with web elements using Selenium’s native methods may not be enough. This is where executing JavaScript in Python Selenium becomes crucial. JavaScript execution allows automation scripts to perform actions that are not directly supported by Selenium’s built-in methods.
In this article, we will explore how to execute JavaScript using Python Selenium WebDriver effectively. We will cover various use cases, such as scrolling the page, clicking hidden elements, extracting data, modifying elements, and handling AJAX requests.
How to Execute JavaScript in Selenium
Selenium provides a built-in method called execute_script() to run JavaScript commands. The syntax is as follows:
driver.execute_script("JavaScript_Code")
Sometimes, elements are not visible until you scroll down. You can use JavaScript to scroll to a specific position or until an element is in view:
from selenium import webdriver
# Initialize the driver
driver = webdriver.Chrome()
driver.get(""https://automationbysqatools.blogspot.com/2021/05/dummy-website.html)
# Scroll down by 1000 pixels
driver.execute_script("window.scrollBy(0,1000);")
Alternatively, scroll to an element:
element = driver.find_element("id", "element_id")
driver.execute_script("arguments[0].scrollIntoView();", element)
Some elements are hidden due to overlays or display properties. Use JavaScript to forcefully click them:
element = driver.find_element("id", "hidden_button")
driver.execute_script("arguments[0].click();", element)
If an element’s text is dynamically generated via JavaScript, traditional Selenium methods might fail. Instead, execute JavaScript to retrieve the content:
text = driver.execute_script("return document.getElementById('element_id').innerText;")
print(text)
You can also use JavaScript to modify the DOM elements dynamically:
driver.execute_script("document.getElementById('element_id').value='New Value';")
Sometimes, elements take time to load due to AJAX. You can use JavaScript to check when all AJAX calls are complete:
driver.execute_script("return jQuery.active == 0;")
JavaScript executed in Selenium can also return values, making it useful for retrieving attributes, inner text, and other information.
page_title = driver.execute_script("return document.title;")
print("Page Title:", page_title)
element = driver.find_element("id", "element_id")nattribute = driver.execute_script("return arguments[0].getAttribute('href');", element)
print(attribute)
Some elements are disabled by default. Use JavaScript to enable and interact with them:
driver.execute_script("document.getElementById('submit_button').removeAttribute('disabled');")
To set cookies manually:
driver.execute_script("document.cookie = 'username=JohnDoe';")
Modify element styles dynamically:
driver.execute_script("document.getElementById('box').style.backgroundColor = 'red';")
try-except blocks to catch errors.WebDriverWait when necessary.from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "element_id")))
driver.execute_script("arguments[0].click();", element)
When automating web applications, handling dropdown menus is a crucial task. Selenium WebDriver, a powerful tool for web automation, provides multiple ways to interact with dropdowns efficiently. In this guide, we will explore various methods to handle dropdowns in Python Selenium with practical examples.
A dropdown menu is an HTML element that allows users to select an option from a list. These elements are commonly created using the <select> tag. Selenium provides the Select class to interact with such dropdown elements easily.
Before handling dropdowns, ensure you have Selenium installed in your Python environment.
Now, import the necessary modules:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select
This is the most common way to select an item from a dropdown. The select_by_visible_text() method is used to select an option based on its displayed text.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
# Initiate Webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
# Launch dummy website
driver.get("https://automationbysqatools.blogspot.com/2021/05/dummy-website.html")
# Select dropdown one element
drop_down_element = driver.find_element(By.ID, "admorepass")
select_obj = Select(drop_down_element)
# Select dropdown option with select_by_visible_text
select_obj.select_by_visible_text("Add 1 more passenger (100%)")
# Select country dropdown element
country_dd = driver.find_element(By.ID, "billing_country")
select_obj2 = Select(country_dd)
select_obj2.select_by_visible_text("India")
time.sleep(5)
# Close the Browser
driver.close()
If you know the position of the option, you can select it using select_by_index().
dropdown.select_by_index(2) # Selects the third option (Index starts at 0)
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
# Initiate Webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
# Launch dummy website
driver.get("https://automationbysqatools.blogspot.com/2021/05/dummy-website.html")
# Select add more passenger dropdown element
drop_down_element = driver.find_element(By.ID, "admorepass")
select_obj = Select(drop_down_element)
# Select value by select_by_index() method
select_obj.select_by_index(2)
# Select country dropdown element
country_dd = driver.find_element(By.ID, "billing_country")
select_obj2 = Select(country_dd)
# Select value by select_by_index() method
select_obj2.select_by_index(10)
time.sleep(5)
# Close the Browser
driver.close()
Each dropdown option has a value attribute that can be used for selection.
dropdown.select_by_value("option2") # Selects the option with value "option2"
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
# Initiate Webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
# Launch dummy website
driver.get("https://automationbysqatools.blogspot.com/2021/05/dummy-website.html")
# Select add more passenger dropdown element
drop_down_element = driver.find_element(By.ID, "admorepass")
select_obj = Select(drop_down_element)
# Select dropdown option by value option
select_obj.select_by_value("3")
# Select country dropdown element
country_dd = driver.find_element(By.ID, "billing_country")
select_obj2 = Select(country_dd)
select_obj2.select_by_value("BE") # Belarus country
time.sleep(10)
# Close the Browser
driver.close()
Sometimes, you may need to extract all options from a dropdown.
options = dropdown.options
for option in options:
print(option.text) # Prints all available options
If the dropdown allows multiple selections, you can deselect options using:
dropdown.deselect_by_index(1)
dropdown.deselect_by_value("option2")
dropdown.deselect_by_visible_text("Option 3")
dropdown.deselect_all() # Clears all selections
Some dropdowns are not built using the <select> tag. Instead, they rely on div, span, or ul/li elements. In such cases, JavaScript execution or direct element interaction is required.
dropdown_button = driver.find_element(By.XPATH, "//div[@class='dropdown']") dropdown_button.click() option_to_select = driver.find_element(By.XPATH, "//li[text()='Option 1']") option_to_select.click()
For complex dropdowns, JavaScript can be used:
script = "document.querySelector('css-selector-for-dropdown').value='option_value'"
driver.execute_script(script)
Selenium is one of the most widely used frameworks for automating web browsers. It provides robust features to interact with web elements, navigate pages, and handle pop-ups efficiently. One of the critical aspects of web automation is handling alerts, which appear as pop-ups and require user interaction. In this comprehensive guide, we will explore the different types of alerts and how to handle them using Python Selenium.
Alerts in Selenium can be broadly categorized into three types:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.alert import Alert import time
A simple alert consists of a message and an OK button. Selenium provides the switch_to.alert method to interact with alerts.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
# Open a webpage with an alert
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")
# Click button to launch alert
driver.find_element(By.ID, "btnShowMsg").click()
time.sleep(2)
# Create alert object
alert = Alert(driver)
print(alert.text)
time.sleep(2)
# Accept alert
alert.accept()
# Close browser
driver.quit()
A confirmation alert contains an OK and Cancel button, requiring user interaction.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
# Open a webpage with an alert
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")
confirm_btn = driver.find_element(By.ID, "button")
confirm_btn.click()
time.sleep(2)
# Create alert object
alert = Alert(driver)
print(alert.text)
time.sleep(2)
# Accept the alert
alert.accept()
UI_msg = driver.find_element(By.ID, "demo").text
print(UI_msg)
assert UI_msg == "You pressed OK!"
confirm_btn = driver.find_element(By.ID, "button")
confirm_btn.click()
# Dismiss the alert
alert.dismiss()
UI_msg_cancel = driver.find_element(By.ID, "demo").text
print(UI_msg_cancel)
assert UI_msg_cancel == "You pressed Cancel!"
# Close Browser
driver.quit()
A prompt alert allows the user to enter input before dismissing the alert.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.alert import Alert
# Initialize WebDriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
# Open a webpage with an alert
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")
# Click button to launch prompt alert popup
prompt_box = driver.find_element(By.ID, "promptbtn")
prompt_box.click()
time.sleep(3)
# Create alert object
alert_prompt = Alert(driver)
new_value = "SQA"
# Send text to prompt box
alert_prompt.send_keys(new_value)
time.sleep(3)
# Accept the alert
alert_prompt.accept()
# Verify text on UI
ui_msg = driver.find_element(By.ID, "prompt")
expected_msg = f"Hello {new_value}! How are you today?"
assert ui_msg == expected_msg
time.sleep(5)
prompt_box = driver.find_element(By.ID, "promptbtn")
prompt_box.click()
time.sleep(3)
# Dismiss the prompt
alert_prompt.dismiss()
ui_msg = driver.find_element(By.ID, "prompt")
expected_msg = f"User cancelled the prompt."
assert ui_msg == expected_msg
# Close browser
driver.quit()
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert
# Initialize WebDriver
driver = webdriver.Chrome()
driver.get("https://automationbysqatools.blogspot.com/2020/08/alerts.html")
try:
WebDriverWait(driver, 10).until(EC.alert_is_present())
driver.find_element(By.ID, "btnShowMsg").click()
time.sleep(2)
alert = Alert()
print("Alert found: ", alert.text)
alert.accept()
except:
print("No alert present")
# Close Browser
driver.quit()