Python Selenium Automation Testing Guide
Python Selenium Automation Testing Guide
Automation Testing is a software testing technique that uses automated tools and scripts to perform
tests on a software application. The main goal is to ensure that the software behaves as expected and
to catch any defects or errors early in the development process. Automation testing is particularly useful
for repetitive test cases, regression testing, and scenarios with large datasets.
1. Unit Testing:
Ensures that new changes or additions to the software do not adversely affect existing
features.
Automates previously executed test cases to catch regressions.
5. Performance Testing:
Measures the system's performance under various conditions such as load, stress, and
scalability.
Ensures the application can handle a specified level of load without degradation.
6. Load Testing:
Examines how well the system performs under specific load conditions.
Identifies performance bottlenecks and potential issues related to system resources.
7. End-to-End Testing:
Now, let's delve into automation testing using Selenium and Python.
1. Python:
Make sure Python is installed on your machine. You can download it from [Link]
([Link]
2. Selenium WebDriver:
Install the Selenium WebDriver for Python using the following command:
Download the web driver for the browser you want to automate (e.g., ChromeDriver for Google
Chrome, GeckoDriver for Mozilla Firefox). Ensure it's in your system's PATH or provide the
path in your script.
Webdriver
A WebDriver, in the context of Selenium, is a tool or an interface that allows you to interact with web
browsers and automate the testing of web applications. It provides a programming interface to control
and manipulate a browser's behavior, enabling automated testing of web applications across different
browsers and platforms.
1. Automation Interface:
WebDriver serves as an automation interface that allows you to script interactions with web
browsers using programming languages like Python, Java, C#, Ruby, etc.
2. Cross-browser Testing:
WebDriver enables cross-browser testing, allowing you to run your tests on different browsers
like Chrome, Firefox, Safari, and others. This is crucial for ensuring that your web application
behaves consistently across various browsers.
3. Interacting with Web Elements:
WebDriver provides methods to interact with various web elements such as buttons, text
fields, checkboxes, and more. You can perform actions like clicking, typing, submitting forms,
and validating content.
4. Navigation:
You can use WebDriver to navigate through different pages of a website by opening URLs,
clicking links, or using back and forward navigation.
5. JavaScript Execution:
WebDriver allows the execution of JavaScript code within the context of a web page. This is
useful for handling dynamic elements and performing complex interactions.
6. Screenshot Capture:
WebDriver provides the capability to capture screenshots during test execution. This is useful
for visually verifying the state of the application at different points in your test.
7. Headless Browsing:
WebDriver supports headless browser testing, which means you can run tests without a
graphical user interface. This is useful for running tests in environments without a display
server.
8. Parallel Test Execution:
WebDriver can be used to run tests in parallel, improving the efficiency of test execution and
reducing the overall test run time.
9. Integration with Testing Frameworks:
WebDriver is often used in conjunction with testing frameworks like JUnit, TestNG, or pytest to
structure and organize test code, manage test data, and report test results.
10. Open Source:
Selenium WebDriver is open source, making it widely adopted and supported by a large
community. This community-driven development ensures continuous improvement and
compatibility with the latest web technologies.
Code Explanation:
1. from selenium import webdriver : Import the webdriver module from the selenium
library. This module provides a way to automate web browsers.
2. chrome_driver = [Link]() : Create an instance of the Chrome webdriver, which
will open the Chrome browser with a blank tab.
3. chrome_driver.maximize_window() : Maximize the Chrome browser window to make it full-
screen.
4. firefox_driver = [Link]() : Create an instance of the Firefox webdriver, which
will open the Firefox browser.
5. firefox_driver.maximize_window() : Maximize the Firefox browser window.
6. edge_driver = [Link]() : Create an instance of the Edge webdriver, which will open
the Edge browser.
7. edge_driver.maximize_window() : Maximize the Edge browser window.
Make sure you have the required browser drivers ([Link], [Link], and
[Link]) available in your system PATH or provide their paths explicitly in the webdriver
instantiation if they are not in the PATH.
Note: In Seleniuim4.0 and later versions drivers not reuqired to download as it's already
download from server, even no need to specify the driver Path
1. close() :
The close() method is used to close the current browser window or tab that the WebDriver
is currently handling.
It leaves other open browser windows or tabs unaffected.
It is generally used when you want to close a specific browser window or tab, but keep the
WebDriver session running.
2. quit() :
The quit() method is used to exit the entire WebDriver session, closing all open browser
windows or tabs associated with that WebDriver instance.
It not only closes the browser windows but also releases the associated driver executable
process and resources.
It is recommended to use quit() at the end of your script to ensure all resources are
properly released.
1. Resource Management:
Browsers consume system resources. If you have multiple browser windows or tabs open,
they can collectively use a significant amount of memory. Closing unnecessary windows helps
manage resources efficiently.
2. Clean Test Environment:
In automated testing, it's crucial to start with a clean and consistent state for each test. Closing
or quitting browsers ensures that each test starts with a fresh browser instance.
3. Preventing Memory Leaks:
Closing or quitting the browser helps prevent memory leaks. Not closing browser instances
properly may lead to memory buildup over time, causing instability or unexpected behavior.
4. Driver Cleanup:
The quit() method releases the WebDriver executable process and resources. This is
important, especially if your script spawns multiple browser instances during its execution.
Failing to quit the WebDriver could result in lingering processes.
In summary, while close() is used to close a specific browser window, quit() is used to terminate
the entire WebDriver session, closing all associated windows and releasing resources. Properly
managing browser instances ensures efficient resource utilization and a clean testing environment. It's
a good practice to use quit() at the end of your script to ensure proper cleanup.
In [10]: 1 # Import the webdriver module from the selenium library
2 from selenium import webdriver
3 import time
4
5 # Opening browsers
6 chrome_driver = [Link]()
7 print("Openning Chrom browser")
8 firefox_driver = [Link]()
9 print("Openning Firefox browser")
10 edge_driver = [Link]()
11 print("Openning Edge browser")
12
13
14 [Link](3) # taling 3 secs pause
15 # closing browsers using close() method
16 chrome_driver.close()
17 print("Chrom Closed using close() method")
18 firefox_driver.close()
19 print("Firefox Closed using close() method")
20 edge_driver.close()
21 print("Edge Closed using close() method")
22
23 print("-------------------")
24
25 [Link](4)
26 # Again, Opening browsers
27 chrome_driver = [Link]()
28 print("Openning Chrom browser")
29 firefox_driver = [Link]()
30 print("Openning Firefox browser")
31 edge_driver = [Link]()
32 print("Openning Edge browser")
33
34
35 [Link](3)
36 # closing browsers using quit() method
37 chrome_driver.quit()
38 print("Chrom Closed using quit() method")
39 firefox_driver.quit()
40 print("Firefox Closed using quit() method")
41 edge_driver.quit()
42 print("Edge Closed using quit() method")
Open a website
Open any website or URL using [Link](_website_link_here_)
In [12]: 1 # Import the webdriver module from the selenium library
2 from selenium import webdriver
3
4 # Import the time module for introducing delays in the script
5 import time
6
7 # Create a new instance of the Chrome webdriver
8 driver = [Link]()
9
10 # Open a website (replace the URL with the one you want to open)
11 website_url = "[Link]
12 [Link](website_url)
13
14 # Optionally, maximize the browser window for a better view
15 driver.maximize_window()
16
17 # Do any other interactions or tests on the website as needed
18
19 # Introduce a delay of 5 seconds (useful for observing the browser interaction)
20 [Link](5)
21
22 # Close the browser window
23 [Link]()
Methods:
1. get(url) : Navigates to the specified URL.
[Link]("[Link]
2. find_element(by, value) and find_elements(by, value) : Locates a single or multiple
elements on the page.
element.send_keys("Hello, Selenium!")
[Link]()
[Link]()
value = element.get_attribute("href")
text = [Link]
visible = element.is_displayed()
9. title and current_url : Get the title and current URL of the page.
title = [Link]
current_url = driver.current_url
Classes:
1. [Link] : The main class for WebDriver that provides methods for browser
interactions.
from selenium import webdriver
driver = [Link]()
2. [Link] : Represents an HTML element and provides methods for interacting
with it.
actions = ActionChains(driver)
actions.move_to_element(element).perform()
capabilities = [Link]
driver = [Link](desired_capabilities=capabilities)
These are just a few examples of the many methods, keywords, functions, and classes available in
Selenium. Depending on your testing needs, you may explore more advanced features and utilities
provided by the Selenium library. Always refer to the official Selenium documentation
([Link] selenium dev/documentation/en/) for the most up to date information
Element
In the context of web automation using Selenium, an "element" refers to an HTML element on a web
page. HTML elements are the building blocks of a web page, and they include various types such as
buttons, text fields, checkboxes, links, and more. Selenium allows you to interact with these elements
programmatically.
Selenium provides several methods to locate and interact with elements on a web page. The primary
mechanism for finding elements is the find_element method. Here are some common strategies to
locate elements:
1. By ID:
3. By Class Name:
4. By Tag Name:
5. By Link Text:
7. By XPath:
8. By CSS Selector:
After finding an element, you can perform various actions on it, such as sending keys, clicking,
retrieving attributes, or checking its visibility. For example:
# Clicking a button
[Link]()
Choose the appropriate locator strategy based on the structure of the HTML and the specific attributes
of the elements you want to interact with. It's often helpful to use browser developer tools to inspect the
HTML structure of a webpage and identify suitable locators for elements.
In [ ]: 1 from selenium import webdriver
2 from [Link] import By
3
4 driver = [Link]()
5 [Link]("[Link]
6 driver.find_element([Link], "search")
Wait Conditions
In Selenium, waiting is a crucial aspect of automating web interactions, as it allows the script to
pause execution until a certain condition is met or a specific element becomes available. Waiting is
essential because web pages may take some time to load, and elements may appear or change
dynamically.
1. Implicit Wait:
An implicit wait tells the WebDriver to wait for a certain amount of time before throwing an
exception if an element is not immediately available.
It is set once for the entire session and remains effective until the WebDriver is closed.
E l i P th
In [72]: 1 from selenium import webdriver
2 from [Link] import By
3 driver = [Link]()
4 driver.implicitly_wait(10)
5 # Set implicit wait to 10 seconds, it declare only once at top
6 # Now, any subsequent element lookups will wait up to 10 seconds before raising
7
8 [Link](rahul)
9
10 text = driver.find_element([Link], "autocomplete")
11 text.send_keys("Hello, Rohit!")
12 print(text.get_attribute("value"))
13
14 [Link]()
Hello, Rohit!
2. Explicit Wait:
An explicit wait is a more granular way of waiting for certain conditions before proceeding with
the test.
It allows you to wait for a specific condition to be met before proceeding further in the code.
It is defined for a certain condition and a maximum time limit.
Example in Python using WebDriverWait:
In [7]: 1 # Basic use of Explicit Wait
2 from selenium import webdriver
3 from [Link] import By
4 from [Link] import WebDriverWait
5 from [Link] import expected_conditions as EC
6
7 driver = [Link]()
8 driver.maximize_window()
9
10 mywait = WebDriverWait(driver, 10) # Explicit wait declaration
11
12 [Link](google)
13
14 search = driver.find_element([Link], "q")
15 search.send_keys("Selenium")
16 [Link]()
17
18 # use of explicit wait
19 search_link = [Link](EC.presence_of_element_located(([Link], "//a[contai
20 search_link.click()
21
22
23 # 2nd use of explicit wait
24 open_link = [Link](EC.presence_of_element_located((By.CLASS_NAME, "seleniu
25 print(open_link.text)
26
27 [Link]()
Selenium WebDriver
WebDriverWait in Selenium is a class that provides explicit wait conditions for waiting until certain
conditions are met before proceeding with the execution of the script. It is a part of the Selenium
WebDriver's expected conditions framework.
# Navigate to a webpage
[Link]("[Link]
In this example WebDriverWait is used to wait for the presence of an element with the ID
Both implicit and explicit waits are essential for handling dynamic content, AJAX requests, and ensuring
that the WebDriver does not attempt to interact with elements before they are available on the page.
Explicit waits are generally preferred for their flexibility and precision in handling specific conditions.
Search clicked
Timeout occurred during the explicit wait. Element not found within the specified t
ime.
Alerts/Pop-ups Handling
Handling alerts (pop-ups) in Selenium involves using the Alert interface provided by Selenium. This
interface provides methods to interact with JavaScript alerts, confirms, and prompts. Here's a basic
overview of how you can handle different types of alerts:
1. Handling JavaScript Alerts:
Authentication Pop-up
Handling authentication pop-ups in Selenium involves using a combination of your browser's built-
in features and Selenium commands. Authentication pop-ups are browser-level dialogs that
typically appear when accessing a webpage that requires username and password authentication.
H ' l i Ch W bD i d it dd t th d t id th ti ti
In [66]: 1 from selenium import webdriver
2 import time
3 # Provide authentication credentials
4 username = "admin"
5 password = "admin"
6
7 # Set up Chrome options with authentication credentials
8 chrome_options = [Link]()
9 chrome_options.add_argument('--disable-extensions')
10 chrome_options.add_argument('--disable-infobars')
11 chrome_options.add_argument('--ignore-certificate-errors')
12 chrome_options.add_argument(f'--user-data-dir={username}:{password}@[Link]'
13
14 # Create a WebDriver instance with Chrome options
15 driver = [Link](options=chrome_options)
16
17 # Navigate to a webpage that requires authentication
18 [Link]("[Link]
19
20 # Continue interacting with the page as needed
21
22 [Link](2)
23 # Close the browser window
24 [Link]()
25
Remember to adapt the XPath or other locators based on the structure of the webpage you are working
with. Additionally, uncomment the lines related to accepting or dismissing alerts, confirms, or prompts
based on your specific use case.
Frames/iFrames
In HTML, frames and iframes are used to divide a web page into multiple sections or to embed external
content within a webpage. They allow developers to create a layout where different parts of the
webpage can load content independently.
Frames:
Frames are an older HTML feature that divides a webpage into multiple independent sections, each
with its own HTML document. The <frame> tag is used to define each frame, and the <frameset>
tag is used to define the overall structure of frames on the page. Each frame can load a separate HTML
document.
<!DOCTYPE html>
<html>
<head>
<title>Frames Example</title>
</head>
<frameset cols="25%,75%">
<frame src="[Link]" name="frame1">
<frame src="[Link]" name="frame2">
</frameset>
</html>
<!DOCTYPE html>
<html>
<head>
<title>IFrame Example</title>
</head>
<body>
<h2>Main Content</h2>
<iframe src="external_content.html" width="600" height="400" title="Extern
al Content"></iframe>
</body>
</html>
1. Frameset vs. Iframe: Frames are typically defined using the <frameset> tag, while iframes are
defined using the <iframe> tag.
2. Independence: Each frame in a frameset has its own HTML document, whereas an iframe
embeds content within the main HTML document.
3. Communication: Communication between frames can be more challenging and often requires the
use of JavaScript. In iframes, communication is often handled more seamlessly.
4. Browser Support: IFrames are more widely supported in modern browsers, while frames are
considered outdated and are not commonly used in contemporary web development.
5. Responsive Design: IFrames can be more easily integrated into responsive web design
compared to frames.
When developing web applications, it is recommended to use iframes over frames for better
compatibility and maintainability. However, the use of frames and iframes should be done judiciously,
In Selenium, the window handles (often referred to as "window IDs") are not static. They are
dynamically assigned by the browser and can change during the execution of a test script. Each
window or tab opened by the browser is assigned a unique identifier (handle), and these identifiers are
subject to change based on the order in which windows are opened or closed.
When you call driver.window_handles , Selenium returns a list of current window handles. The
order of handles in this list may change if new windows are opened or existing windows are closed.
1. Order of Handles: The order of window handles in the list corresponds to the order in which the
windows were opened, with the first handle representing the main window.
2. Dynamic Nature: Since window handles are dynamic, it's crucial to retrieve the handles when
needed and not rely on hard-coded indices, as they may change.
3. Switching Between Windows: When switching between windows using
driver.switch_to.window(handle) , always use the actual handle obtained from
driver.window_handles .
Example:
Remember to close the windows or tabs appropriately to avoid leaving unnecessary browser instances
running. You can use [Link]() to close the current window and [Link]() to close
the entire browser.
This example assumes that you have opened a new window during the execution of your test script. If
your application opens new windows in response to user actions, you may need to adjust the script
In [122]: 1 from selenium import webdriver
2 from [Link] import By
3 import time
4
5 driver = [Link]()
6 driver.maximize_window()
7 [Link](testauto)
8 driver.implicitly_wait(5)
9
10 wiki = driver.find_element([Link], "Wikipedia1_wikipedia-search-input")
11 wiki.send_keys("Cricket")
12 [Link]()
13
14 # Opening new window tabs using the attribute target="_blank"
15 wiki_links = driver.find_elements([Link], "//div[@id='wikipedia-search-result-
16 for link in wiki_links:
17 [Link]()
18
19 # printing id of current tab
20 current_window_id = driver.current_window_handle
21 print("Id of current window: ", current_window_id)
22
23 # Id of all opened tabs
24 all_opened_windows = driver.window_handles
25 print("List of All Opened Windows ID: ", all_opened_windows)
26
27 # switching windows and printing title with window id
28 for i in all_opened_windows:
29 driver.switch_to.window(i)
30 print(f"Window Tab Title: {[Link](30)}, Window ID: {i}")
31
32 # switching driver to first window
33 driver.switch_to.window(all_opened_windows[0])
34
35 # confirm the title of first window
36 print("Current Window Title: ", [Link])
37
38 # window close
39 # [Link] () # close current window only
40 # [Link]() # close all windows at once
41
42 for i in all_opened_windows:
43 driver.switch_to.window(i)
44 print(f"{[Link](30)} : Closed")
45 [Link]()
46 [Link](2)
Id of current window: 2C072DC543F6D268848B8AE9ADE9446F
List of All Opened Windows ID: ['2C072DC543F6D268848B8AE9ADE9446F', '6C8014ADAB41A
C8C53853C7BE2AE583B', 'A411C329EF48AC8DA5C4015A9D042A46', 'F1E43A7DCE21143351A53990
87382DD8', 'C7C2662CEB0B1DE593909CA4179A7052', '0A198008C8CD48365570D1FE690F0CFF']
Window Tab Title: Automation Testing Practice , Window ID: 2C072DC543F6D268848B8A
E9ADE9446F
Window Tab Title: Cricket in India - Wikipedia , Window ID: 6C8014ADAB41AC8C53853C
7BE2AE583B
Window Tab Title: Cricket pitch - Wikipedia , Window ID: A411C329EF48AC8DA5C401
5A9D042A46
Window Tab Title: Cricket (insect) - Wikipedia , Window ID: F1E43A7DCE21143351A539
9087382DD8
Window Tab Title: Cricket - Wikipedia , Window ID: C7C2662CEB0B1DE593909C
A4179A7052
Window Tab Title: Cricket World Cup - Wikipedia , Window ID: 0A198008C8CD48365570D1
FE690F0CFF
Current Window Title: Automation Testing Practice
Automation Testing Practice : Closed
Cricket in India - Wikipedia : Closed
Cricket pitch - Wikipedia : Closed
Cricket (insect) - Wikipedia : Closed
Cricket - Wikipedia : Closed
Cricket World Cup - Wikipedia : Closed
chrome_options = [Link]()
chrome_options.add_argument("--window-size=1200,800")
driver = [Link](chrome_options=chrome_options)
chrome_options = [Link]()
chrome_options.add_argument("--disable-extensions")
driver = [Link](chrome_options=chrome_options)
3. Headless Mode:
You can run the browser in headless mode, which means without a graphical user interface. This is
useful for running tests in the background without displaying the browser window.
chrome_options = [Link]()
chrome_options.add_argument("--headless")
driver = [Link](chrome_options=chrome_options)
chrome_options = [Link]()
chrome_options.add_argument("--ignore-certificate-errors")
driver = [Link](chrome_options=chrome_options)
chrome_options = [Link]()
chrome_options.add_argument("--lang=en-US")
driver = [Link](chrome_options=chrome_options)
6. Incognito Mode:
To open the browser in incognito (private browsing) mode, use the --incognito option.
chrome_options = [Link]()
chrome_options.add_argument("--incognito")
driver = [Link](chrome_options=chrome_options)
7. Setting Proxy:
You can set a proxy for your browser session using the --proxy-server option.
chrome_options = [Link]()
chrome_options.add_argument("--proxy-server=[Link]
driver = [Link](chrome_options=chrome_options)
8. Notifications/Alert Settings
To disable notifications in a Chrome browser controlled by Selenium, you can use the --disable-
notifications argument. Here's an example in Python:
chrome_options = [Link]()
chrome_options.add_argument("--disable-notifications")
driver = [Link](chrome_options=chrome_options)
Web Table
Working with web tables in Selenium involves locating the table, navigating its rows and columns, and
extracting or interacting with the data. Let's go through some common tasks with web tables using
Selenium in Python.
<table id="example">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>USA</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
<td>Canada</td>
</tr>
<!-- More rows... -->
</tbody>
</table>
driver = [Link]()
[Link]("[Link]
[Link]()
driver = [Link]()
[Link]("[Link]
Date Picker
In [268]: 1
<class 'str'>
mm/dd/yyyy
09/12/2023
11/09/2020
Mouse Operations
Selenium provides a class called ActionChains that allows you to perform various mouse and
keyboard actions. Here are some common mouse operations along with examples using Selenium in
Python:
1. Click
Perform a left-click on an element:
from selenium import webdriver
from [Link] import By
from [Link].action_chains import ActionChains
driver = [Link]()
[Link]("[Link]
In [ ]: 1
2. Double Click
Perform a double-click on an element:
driver = [Link]()
[Link]("[Link]
[Link]()
Slider
In [357]: 1 from selenium import webdriver
2 from [Link].action_chains import ActionChains
3 from [Link] import By
4 import time
5
6 driver = [Link]()
7
8 driver.implicitly_wait(10)
9 driver.maximize_window()
10
11 [Link]("[Link]
12
13 slider = driver.find_element([Link], "//div[@id='slider']//span")
14 print(slider.get_attribute("style"))
15 print("Location: ", [Link])
16 act = ActionChains(driver)
17
18 [Link](4)
19 act.drag_and_drop_by_offset(slider,200,0).perform()
20
21 slider = driver.find_element([Link], "//div[@id='slider']//span")
22 print(slider.get_attribute("style"))
23 print("Location: ", [Link])
24
25 [Link](3)
26 [Link]()
left: 0%;
Location: {'x': 762, 'y': 1096}
left: 63%;
Location: {'x': 959, 'y': 1096}
Scroll Page
To scroll a page in Selenium using Python, you can use the execute_script method to execute
JavaScript code that performs the scrolling. Here are a few examples:
1. Scroll Down
No of Pixels moved: 0
No of Pixels moved: 10
No of Pixels moved: 30
No of Pixels moved: 60
No of Pixels moved: 100
No of Pixels moved: 150
No of Pixels moved: 210
No of Pixels moved: 280
No of Pixels moved: 360
No of Pixels moved: 450
These examples use the execute_script method to execute JavaScript code that manipulates the
window object. Adjust the scroll values or customize the scrolling behavior based on your specific
requirements.
Keep in mind that some websites may use dynamic loading or infinite scrolling, so you might need to
h dl h i i di l
Keyboard Actions
Selenium provides the Keys class to simulate keyboard actions. Here are some common keyboard
actions you can perform using Selenium in Python:
1. Typing Text
notes
4. Special Keys
These are just a few examples of keyboard actions you can perform with Selenium. The Keys class
provides various keys you can use, and you can combine them to create more complex interactions.
Adjust the examples based on your specific requirements and the structure of the webpage you are
working with.
Download and Upload Files
Downloading and uploading files using Selenium involves interacting with file input elements and
system dialogs. Here are examples for both scenarios:
1: Download Files
Downloading start...
In [113]: 1 # Detailed video for Download and Upload with many browser settings
2 from [Link] import HTML
3 html_code = """
4 <iframe width="560" height="315" src="[Link]
5 """
6 display(HTML(html_code))
7
Upload File
In [116]: 1 from selenium import webdriver
2 from [Link] import By
3 import time
4
5 driver = [Link]()
6 [Link]("[Link]
7
8 # Locate the file input element
9 file_input = driver.find_element([Link], "file-input")
10
11 # Provide the path to the file you want to upload
12 file_path = "C:/Selenium/Projects/img_10.png"
13 file_input.send_keys(file_path)
14 print("File uploaded")
15
16 # Perform other actions as needed
17 [Link](10)
18 [Link]()
19
Bootstrap Dropdown
Screenshot
Taking screenshots in Selenium is a useful technique for debugging, capturing webpage states, or
validating test results. Here's how you can take screenshots using Selenium in Python:
1. Full Screen Screenshot
saved
Saved
3. Scrolling down and capturing multiple screenshots
3883
Handle Cookies
Cookies in Web Development:
Cookies are small pieces of data stored on a user's computer by the web browser while browsing a
website. They are commonly used to remember user preferences, login sessions, and other information
that enhances the user experience. Cookies are sent between the client (browser) and the server with
each HTTP request.
Types of Cookies:
1. Session Cookies: Temporary cookies that are deleted when the browser is closed.
2. Persistent Cookies: Stored on the user's device for a specified period, even after the browser is
closed.
Selenium provides methods to interact with cookies. Here are some common operations:
3. Add a Cookie:
4. Delete a Cookie:
E l
In [94]: 1 # Get and add cookies
2 from selenium import webdriver
3
4 # Create a webdriver instance (e.g., Chrome)
5 driver = [Link]()
6
7 # Navigate to a website
8 [Link](nopcom)
9
10 # Get All Cookies
11 cookies = driver.get_cookies()
12
13 type(cookies)
14
15 # First Cookie details
16 cookies[1]
17
18 for cookie in cookies:
19 print(cookie,"\n")
20
21 # Get one cookie by cookie name
22 cookie1 = driver.get_cookie(".[Link]")
23 print(cookie1)
24
25 print("Domain: ", [Link]("domain"))
26
27 for key in cookie1:
28 print(f"{[Link](10)} : {cookie[key]}")
29
30 print("No of cookies present: ", len(cookies))
31
32 # Add a new cookie
33 driver.add_cookie({"name":"credential","value":"username"})
34
35 updated_cookies = driver.get_cookies()
36 print("No of cookies present: ", len(updated_cookies))
37
38 for key in updated_cookies:
39 print("Cookie name: ",key['name'])
40
41 [Link]()
{'domain': '[Link]', 'expiry': 1733801761, 'httpOnly': False, 'name':
'.[Link]', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'c%3Den-U
S%7Cuic%3Den-US'}
Total No of Cookies 3
{'domain': '[Link]', 'expiry': 1733802209, 'httpOnly': False, 'name':
'.[Link]', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'c%3Den-U
S%7Cuic%3Den-US'}
In [ ]: 1