有没有办法使用 selenium python 向元素添加带有值的新属性? [英] Is there a way to add a new attribute with a value to an element using selenium python?

查看:82
本文介绍了有没有办法使用 selenium python 向元素添加带有值的新属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 HTML

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

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

I am trying to add 3 new attributes to make it like

<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">

我想补充:

  • style="display: block;左边距:自动;margin-right: auto;"
  • data-mce-style="display: block;左边距:自动;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

推荐答案

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

To add the three new attributes you need to use Selenium's execute_script() method.

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

Now, you want to add the following attributes:

  • style="display: block;左边距:自动;margin-right: auto;"
  • data-mce-style="display: block;左边距:自动;margin-right: auto;"
  • data-mce-selected=1"

添加它们的方法类似,作为添加属性data-mce-selected=1"的演示,您需要引入WebDriverWait 用于 visibility_of_element_located() 并且您可以使用以下任一定位器策略:

The method for adding them would be similar and as a demonstration to add the attribute data-mce-selected="1" you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • 使用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']"))))
    

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

    You can find a couple of relevant detailed discussions in:

    这篇关于有没有办法使用 selenium python 向元素添加带有值的新属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆