有没有办法使用 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
要添加您需要使用的三个新属性 Selenium 的 execute_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: