I want to change the CSS element style using Python Selenium while doing automation to change the theme color of the page. For example, the page element is as follows:
<div style="background: #e7e7e7">
<div style="border-bottom: #e7e7e7; border-top: #e7e7e7">
I want to change the color from #e7e7e7
to #318c89
, which means I need to find all e7e7e7
in the HTML script and replace all with #318c89
but I have no idea how should I do that.
Thanks in advance.
CodePudding user response:
Try this:
script = "document.body.innerHTML = document.body.innerHTML.replaceAll('#e7e7e7', '#318c89')"
driver.execute_script(script)
CodePudding user response:
This uses JavaScript to replace all text in dom with given text executed by selenium execute JavaScript function.
from selenium import webdriver
from time import sleep
# Run with Chrome window visible
DRIVER_PATH = 'path to driver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get("webpage url")
# change to first colour
js = """
document.body.innerHTML = document.body.innerHTML.replaceAll('#e7e7e7 ', '#318c89')
console.log("Hello World");
"""
driver.execute_script(js)
sleep(10)
# change back
js = """
document.body.innerHTML = document.body.innerHTML.replaceAll('#318c89 ', '#e7e7e7')
console.log("Hello World");
"""
driver.execute_script(js)
sleep(60)
driver.quit()