Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to change an attribute and give it a value with selenium

I have 19 span with the same attribute data-checked

<span id="u25-accordion-panel--61" data-type="checkbox" data-checked style="display: none;"></span>

I want to change the attribute in all the spans, I tried with 1 but I get the following error

options = webdriver.EdgeOptions()
options.add_argument("start-maximized")
driver = webdriver.Edge(options=options)
driver.implicitly_wait(20)
driver.get(
    'https://www.udemy.com/course/angular-10-fundamentos-8-app/')


elem = driver.find_element(By.CSS_SELECTOR,
                           '#udemy > div.ud-main-content-wrapper > div.ud-main-content > div > div > div.paid-course-landing-page__container > div.paid-course-landing-page__body > div > div:nth-child(3) > div > button')
elem.click()

elems = driver.find_elements(By.CSS_SELECTOR,
                             'div.accordion-panel--panel--24beS > span')

driver.execute_script("arguments[0].data-checked = 'checked';", elems[1])
driver.execute_script("arguments[0].data-checked = 'checked';", elems[1])
selenium.common.exceptions.JavascriptException: Message: javascript error: Invalid left-hand side in assignment
  (Session info: MicrosoftEdge=109.0.1518.78)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To change set the value of data-checked attribute for all the accordion-panel elements as checked you can use the setAttribute() method as follows:

  • Code block:

    driver.get('https://www.udemy.com/course/angular-10-fundamentos-8-app/')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#udemy > div.ud-main-content-wrapper > div.ud-main-content > div > div > div.paid-course-landing-page__container > div.paid-course-landing-page__body > div > div:nth-child(3) > div > button"))).click()
    elements = driver.find_elements(By.CSS_SELECTOR, 'div.accordion-panel--panel--24beS > span')
    for element in elements:
        driver.execute_script("arguments[0].setAttribute('data-checked', 'checked')", element)
    
  • Browser Snapshot:

data-checked

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading