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

Question:

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)

Answers:

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

Answered By: undetected Selenium
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.