selenium 对标签属性值更改的方法在网上搜到的最多的就是:
driver.execute_script(js, element)
But... 尝试用这个语法更改class 属性似乎不行... 一番研究下... 找到了这个方法:
driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])",element,Attribute,value)
先看个例子1:
把百度首页的‘百度一下’更改为‘test'
### 代码1
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=chromedriverPath,chrome_options=options)
driver.get('http://www.baidu.com')
path = driver.find_element_by_xpath('//*[@id="su"]')
js= 'arguments[0].value="test"'
driver.execute_script(js,path)
运行的结果,如期望一样:
F12一下:
这一段代码和上面 ’代码1‘ 运行结果一样:
### 代码2
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=chromedriverPath,chrome_options=options)
driver.get('http://www.baidu.com')
# path = driver.find_element_by_xpath('//*[@id="su"]')
# js= 'arguments[0].value="test"'
js='document.querySelector("#su").value="test"'
driver.execute_script(js)
例子2:
把’百度一下‘ class 属性换成'aaaa'
先看一下这个class的初始值,为'bg s_btn'
执行代码 3:
### 代码 3
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=chromedriverPath,chrome_options=options)
driver.get('http://www.baidu.com')
path = driver.find_element_by_xpath('//*[@id="su"]')
js= 'arguments[0].class="aaaa"'
# js='document.querySelector("#su").value="test"'
driver.execute_script(js,path)
执行的结果中,'百度一下‘ class 属性值并没有更改,结果中也无任何报错...
使用下面方法可以更改成功:
driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])",element,Attribute,value)
代码 4:
### 代码 4
from selenium import webdriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=chromedriverPath,chrome_options=options)
driver.get('http://www.baidu.com')
path = driver.find_element_by_xpath('//*[@id="su"]')
# js= 'arguments[0].class="aaaa"'
# js='document.querySelector("#su").value="test"'
# driver.execute_script(js,path)
driver.execute_script("arguments[0].setAttribute(arguments[1],arguments[2])",path,'class','aaaa')
执行结果:
注意:
代码中的’chromedriverPath' 是chrome 驱动在本地的地址(chromedriver.exe 所在的路径)
’path‘ 是’百度一下' 的xpath定位
arguments[0]对应的是'更改的元素'
arguments[1]对应的是'更改的属性'
arguments[2]对应的是'更改之后的值'