Executing a test script across various URLs and different browsers locally using Selenium with Python

I need assistance with running a test script on multiple URLs using both Chrome and Firefox browsers locally on my machine. Each browser must open all the specified URLs in the test script. I have successfully run the test script for multiple URLs, but I am uncertain about how to execute it for different browsers. Although I have researched online resources, they focus on remote testing rather than local execution. Below is the code snippet of my test script:

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

Driver = webdriver.Chrome()

def localitems() :
    local_storage = Driver.execute_script( \
        "var ls = window.localStorage, items = {}; " \
        "for (var i = 0, k; i < ls.length; ++i) " \
        "  items[k = ls.key(i)] = ls.getItem(k);"\
            "return items; ")
    return local_storage;

def sessionitems() :
    session_storage = Driver.execute_script( \
        "var ls = window.sessionStorage, items = {}; " \
        "for (var i = 0, k; i < ls.length; ++i) " \
        "  items[k = ls.key(i)] = ls.getItem(k);"\
            "return items; ")
    return session_storage;

sites = [
    "http://www.github.com",
    "https://tribune.com.pk"
]



 for index, site in enumerate(sites)
        print(index,site)
        Driver.get(site)
        time.sleep(5)
        print('localStorage', localitems())
        print('sessionStorage', sessionitems())
Driver.quit()

Your guidance on incorporating multiple browsers into the test script would be greatly appreciated.

Answer №1

Compile a roster of the drivers and then run your script in the for loop:

drivers = [webdriver.Chrome(), webdriver.Firefox()]

for driver in drivers:
    def localitems():
        local_storage = driver.execute_script( \
            "var ls = window.localStorage, items = {}; " \
            "for (var i = 0, k; i < ls.length; ++i) " \
            "  items[k = ls.key(i)] = ls.getItem(k);" \
            "return items; ")
        return local_storage;


    def sessionitems():
        session_storage = driver.execute_script( \
            "var ls = window.sessionStorage, items = {}; " \
            "for (var i = 0, k; i < ls.length; ++i) " \
            "  items[k = ls.key(i)] = ls.getItem(k);" \
            "return items; ")
        return session_storage;


    sites = [
        "http://www.github.com",
        "https://tribune.com.pk"
    ]

    for index, site in enumerate(sites):
        print(index, site)
        driver.get(site)
        time.sleep(5)
        print('localStorage', localitems())
        print('sessionStorage', sessionitems())
    driver.quit()

It's worth noting that Python follows a naming convention called PEP-8, which suggests using lowercase letters for variable names. Therefore, it's recommended to use driver instead of Driver

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a to-do list application using web.py with an in-memory database

Completely new to web.py, I am eager to dive in and learn. My goal is to tweak the todo list example by utilizing an in-memory database instead of mysql. This is what I came up with: import web db = web.database(dbn="sqlite", db=":memory:") db.query("CR ...

Server log for Selenium Webdriver

Could someone please provide guidance on how to check the webdriver server log? In the past, we were able to view the log by running selenium server from the command line. I am currently using the latest standalone server with firefox driver. I attempted t ...

Ways to troubleshoot Python-Selenium crashing issue when attempting to capture a screenshot

Encountering an error while using selenium 4.0.0 for python selenium.common.exceptions.WebDriverException: Message: unknown error: session deleted due to page crash from unknown error: cannot determine loading status from tab crashed (Session info: headl ...

Tips for extracting data from a website that requires scrolling down repeatedly

I have a specific website where I always need to scroll down to access the information My code is provided below, however, I am not able to retrieve anything from it # -*- coding: UTF-8 -*- import csv from parsel import Selector from time import sle ...

Utilizing keyboard functions to access files beyond Python's scope

Just starting out in the world of programming.... I'm tackling the challenge of creating a program that can be operated through keyboard shortcuts. My goal is to connect specific excel files to these keyboard shortcuts. So far, I've managed to o ...

The Selenium test functions correctly in the production environment, however it encounters issues when run

I am facing an issue with my Vue.js application while writing Selenium tests. The test passes when run against the deployed production version of the app, but fails when run against a local version. When running the app locally, it is not from a build, bu ...

Using Python's Matplotlib library to plot a 2D line graph without the need to sort the

Is there a way to instruct matplotlib not to automatically sort xdata values when plotting a line using matplotlib.lines.Line2D? I need to use custom xticks represented as strings, such as: import matplotlib.pyplot as plt x = ['1','2' ...

Python tutorial: Extracting a particular text row using Selenium when all table rows share the same class

Could anyone help me with a Python script to extract data from this webpage using Selenium? Here's the code snippet: from selenium import webdriver import os from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import B ...

Admin panel in Django does not have static data when using Nginx and Docker

I am facing an issue while trying to run my django app in a Docker container (using nginx, gunicorn, etc.) on my local machine. Everything seems to be working fine, but I am not able to see the static data. The error that I see in the docker logs is as fol ...

Display a table image in a new location on the HTML page through dynamic rendering

I am working on a task where I need to retrieve the content of the 'Photo' column for a specific row in a table and display the corresponding image on an HTML page. The 'image' column contains paths to jpg images. For instance, if we s ...

Tips for successfully including a variable in a JSON string within a bash script

Below is a script that retrieves command output from a host and saves it to a file /tmp/${stcl}_aggr.txt. The content of this file is then stored in a variable body=$(cat /tmp/${stcl}_aggr.txt). When I try to use the Variable body in a JSON array as " ...

Finding web elements using Xpath in Selenium, specifically targeting elements within a dropdown menu

I'm having trouble using driver.FindElements on a dropdown list to help me count the elements in it. I'm having difficulty with getting the XPath to work with this HTML snippet: <select class="form-control form-control-lg ng-valid ng-dirty ng ...

Looking for assistance with identifying and matching patterns

Issue: Looking for a regex that matches sentences starting with hi (case insensitive) but not immediately followed by a space and the letter "d". My current regex pattern: [hi|HI|hI|Hi][^ d|D][a-zA-Z ]* Despite my efforts, I'm puzzled as to why the ...

Achieving validation for individual items in Python step by step

I have a program that is functioning properly, but I need it to validate after each number input rather than at the end. How can I modify it to check after each number while maintaining separate functions for each task? Whenever I try to return a number ...

Disabling "Unresponsive script" alerts in Selenium and Firefox: What is the best approach?

Currently, I am utilizing Selenium Client 2.4.0 on Mac 10.6.6 with Firefox 5. When using the WebBackedSeleniumDriver, a "selenium.getEval" command triggers a warning in Firefox: "Warning: Unresponsive script. A script on this page may be busy, or it may ...

What steps can be taken to apply feature scaling in this regression model effectively?

While taking a course on Python Machine Learning, I encountered a warning message indicating an issue with my code. The code snippet in question is as follows: # SVR(Support Vector Regression) # Importing necessary libraries import numpy as np import mat ...

A server hosting two flask apps, both deployed successfully but one encountering an unresponsive '/' route

Issue I am facing a problem with two Flask applications deployed on the same GCP compute engine with an nginx server. The first application is on the main domain: myapp.com. The second application is on a subdomain: example.myapp.com. All routes from t ...

Using Numpy to transform a sequence of whole numbers into hexadecimal format

I am faced with a challenge involving an image array transformed into a 16 x 1000000 array of 4 values each, represented as 2-bit integers using Numpy. A snippet of the array is shown below. My goal is to convert each column into a hexadecimal word in the ...

Exploring Python techniques for restructuring a multidimensional array with multiple dimensions

Imagine I have an array similar to this: [[1,2], [3,4,5]] and I want to transform it into this format: [[[1],[2]], [[3],[4],[5]]] Is there a straightforward way to achieve this in Python? I am aware that reshaping is simple when the second dimension is ...

Is it possible to use the Input() function to modify the file name in this code? I am looking for a valid version of this code

Is there a way to modify this code snippet from GeeksforGeeks? The code runs correctly except for the line "with open("/content/gdrive/My Drive/xyz.exe "wb") as file:" How can I use the input() function to change the filename xyz.exe? import requests f ...