14

How can I edit an element in a browser that I opened with Python 2.7 Selenium. Let's say I have this element:

<span id="some-random-number">100</span>

I know that you can find the text with:

driver.find_element_by_id("some-random-number").text

but I want the text of the element change to let say 200 so:

<span id="some-random-number">200</span>

How can I do it? Also except from text can I also edit element's attribute like for example this:

<div class="something" style="transition: transform 1000ms bla bla bla"></div>

Can my script read the attribute and edit the 1000 ms into different value?

3 Answers 3

13

Here is your answer -

  1. Change the text of element -

    driver.execute_script("document.getElementById('some-random-number').innerHTML = '200';");
    

    or

            element =driver.find_element_by_id("some-random-number")
            driver.execute_script("arguments[0].innerText = '200'", element)
    
  2. Change or set an attribute value

            element =  driver.find_element_by_class_name("something");
            driver.execute_script("arguments[0].setAttribute('style', 'transition: transform 2500ms bla bla bla')", element);
    
9

Try this:

element =driver.find_element_by_id("some-random-number")
driver.execute_script("arguments[0].innerText = '200'", element)
1

For your second question:

div_elem = driver.some_method_to_find_element()
new_style = div_elem.get_attribute('style').replace('transform 1000ms', 'transform 200ms')
driver.execute_script('arguments[0].setAttribute("style", "%s")' % new_style, div_elem)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.