有没有办法使用 selenium python 向元素添加具有值的新属性?

Is there a way to add a new attribute with a value to an element using selenium python?

这是HTML

<img src="//www.shahidpro.tv/uploads/articles/220cc817.jpg" width="408" height="605" vspace="" hspace="" border="0" alt="">

我正在尝试添加 3 个新属性以使其像

<img src="//www.shahidpro.tv/uploads/articles/220cc817.jpg" width="408" height="605" vspace="" hspace="" border="0" alt="" style="display: block; margin-left: auto; margin-right: auto;" data-mce-style="display: block; margin-left: auto; margin-right: auto;" data-mce-selected="1">

我要补充:

我试过了:

image = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "body.mce-content-body#tinymce > p/a/img")))
browser.execute_script("arguments[0].style='display: block; margin-left: auto; margin-right: auto;'", image)
browser.execute_script("arguments[0].data-mce-style='display: block; margin-left: auto; margin-right: auto;'", image)
browser.execute_script("arguments[0].data-mce-selected='1'", image)     ` but got no results nor errors

假设您可以找到要更改的 element。 您可以使用 js 添加新属性:

driver.execute_script("arguments[0].setAttribute('style', 'display: block; margin-left: auto; margin-right: auto;');", element)

要添加您需要使用 execute_script() 方法的三个新属性。

现在,您要添加以下属性:

  • style="display: block; margin-left: auto; margin-right: auto;"
  • data-mce-style="display: block; margin-left: auto; margin-right: auto;"
  • data-mce-selected="1"

添加它们的方法类似,作为添加属性 data-mce-selected="1" 的演示,您需要引入 for the visibility_of_element_located() and you can use either of the following :

  • 使用CSS_SELECTOR:

    element = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img[src='//www.shahidpro.tv/uploads/articles/220cc817.jpg']")))
    browser.execute_script("arguments[0].setAttribute('value','28/02')", element)
    
  • 使用 XPATH 并在一行中:

    browser.execute_script("arguments[0].setAttribute('data-mce-selected','1')", WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[@src='//www.shahidpro.tv/uploads/articles/220cc817.jpg']"))))
    

参考资料

您可以在以下位置找到一些相关的详细讨论:

  • How to use javascript to set attribute of selected web element using selenium Webdriver using java?
  • Python - How to edit href attribute in source code before clicking using Selenium