我想使用 Python Selenium 更改 CSS 元素樣式,同時進行自動化以更改頁面的主題顏色。例如頁面元素如下:
<div style="background: #e7e7e7">
<div style="border-bottom: #e7e7e7; border-top: #e7e7e7">
我想將顏色從 更改#e7e7e7為#318c89,這意味著我需要e7e7e7在 HTML 腳本中找到所有內容并將所有內容替換為,#318c89但我不知道該怎么做。
提前致謝。
uj5u.com熱心網友回復:
嘗試這個:
script = "document.body.innerHTML = document.body.innerHTML.replaceAll('#e7e7e7', '#318c89')"
driver.execute_script(script)
uj5u.com熱心網友回復:
這使用 JavaScript 用 selenium execute JavaScript 函式執行的給定文本替換 dom 中的所有文本。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/337990.html
