Using JavaScript to set attribute values in Python Selenium, these values are cleared after each update

Assuming :

                    for i in list('{}'.format(value)):
                        self.browser.execute_script(
                            "arguments[0].setAttribute('value', '{}');".format(i.replace('\n', '')),
                            self.browser.find_element_by_xpath("{}".format(xpath)))

Let's assume the string to be typed is "asd" It types 'a' first, then deletes it and types 's', deletes 's' and types 'd', and clears when another action is taken (typing in another field or clicking on another element)

Example of HTML element :

<input type="text" class="validate-input input-error" placeholder="Enter Token" value="">

Note: The clearing process remains the same even if the loop is not used and the value is directly passed to the JavaScript function.

EDIT: It is required that the element selector be by xpath.

Answer №1

Check out this tried and tested solution for using XPath to set a value in JavaScript
Note: I rely on the webdriver_manager to handle browsers

def setInputValueByXpath(xpath, inputValue):
    script = "document.evaluate('" + xpath + "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value = '" + inputValue + "'"
    driver.execute_script(script)

if __name__ == '__main__':
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get('https://www.google.com')

    // call the function above with desired xpath and corresponding value
    setInputValueByXpath('//*[@name="q"]', 'Paint Drying')

    // simulate a search by hitting the enter key
    driver.find_element_by_xpath('//*[@name="q"]').send_keys(Keys.RETURN) 
    time.sleep(5)

    driver.quit()

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

Tips on obtaining the total element count within a specific div using Selenium

I am currently working on retrieving the count of search results when using the MakeMyTrip application to search for flights from Hyderabad to Bangalore. While I have successfully managed to extract the text, I am now looking for a way to confirm the numbe ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

What steps should I take to resolve a plugin error specifically related to index.js while using Cypress?

I am encountering an error in Cypress A plugin has thrown the following error, causing our tests to stop running due to a plugin crash. Please verify your plugins file (/home/dev2/Desktop/kavitaSeffcon/CypressProject/cypress/plugins/index.js) Error: ENOE ...

Can a static text be displayed randomly using Javascript?

What I'm searching for is a unique text display feature that's different from scrolling. I envision a subtle fade in/out effect, but it's not necessary. The main goal is to fit within a small area on a website with limited vertical space - ...

Steps for creating a while loop that continuously inputs prices until the user enters 0:

I am hoping to create a simple Python code that allows users to input prices from a shopping trip, with the loop ending when they input 0. Once the loop stops, I'd like to display the total number of items, average price, and total price using an else ...

Scrapy spider malfunctioning when trying to crawl the homepage

I'm currently using a scrapy scrawler I wrote to collect data from from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from .. import items clas ...

Struggling to input data into Excel using Selenium WebDriver

I encountered an issue while attempting to write two strings to an Excel sheet using the following code. The error message I received was: java.lang.IllegalArgumentException: Sheet index (0) is out of range (no sheets) FileOutputStream fout=new FileOutput ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

What is the best way to set up a peewee SQLite database on the fly?

Currently, I am using the peewee library to work with my sqlite database. Within a module, I have defined various database models as per the examples provided in the documentation. The initialization of the database is outlined in the initial code snippet: ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

What is the best way to eliminate all borders from a select box?

Is there a way to completely remove all borders from the selectbox using either CSS or JQuery? The code snippet is as follows: <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option& ...

Transferring an Applescript list to ExtendScript in Javascript as an array for use in InDesign

Situation Background I have a large number of Applescripts (AS) that designers rely on in InDesign to streamline production workflows. These AS scripts handle a lot of OS interactions that JavaScript cannot replicate, so transitioning away from AS is not ...

Utilizing EventEmitters for cascading operations in Angular 2 dropdown menus

I have a form with several cascading drop-downs - the selection in one drop-down determines the options available in the next. Each drop-down retrieves its values from an async data service, and Angular EventEmitter is used to handle events and populate su ...

Is it possible to simultaneously verify if an array is empty within an Object along with checking the other fields?

Let's say I have an object that has the following structure: filter: { masterName: '', service:[], } What is the best way to determine if both the array and masterName field are empty? ...

Swiper JS eternal carousel transition

While trying to create an endless carousel using swiper js on my website, I encountered a slight vibration between the slides that makes it seem like the images are flickering. Despite my efforts, I have been unable to find a solution to this issue. Any as ...

an alternative for checking if the script is being run as the main program:

I have a main.py file along with a module called gui.py. My goal is to compile them to Cython and then create an executable which includes the following code: import gui if __name__ == '__main__': gui() In the gui.py module, I have some cod ...

One way to shuffle outcomes from two querysets in a Django template

Hey there! I'm interested in finding out how we can display results from two different querysets in a Django template. This is what my views.py looks like: def index(request): answers = Answer.objects.filter(user=request.user) questions = Qu ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

Trying to assign a property to an undefined variable inside a function

At the moment, I am configuring error messages on a login page for an extension using vue, and encountering issues within the importCreds() function. data(){ return { url:'', apikey:'', error:'', } }, meth ...

How to access global variables in node.js modules?

I'm looking to move some functionality to a new file called helpers.js. Below is the code that I have put in this file. How can I access the app variable within my method so that I can retrieve the config element called Path? Helpers = { fs: requ ...