You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium Python为页面body添加指定背景图片样式?

用Selenium Python给页面添加自定义样式实现背景图

直接通过Selenium执行JavaScript代码就能实现,核心思路是创建<style>标签并插入到页面中,具体步骤如下:

  • 初始化浏览器并打开目标页面
  • 定义要添加的样式内容
  • 执行JS代码创建style元素,将样式内容注入后添加到页面的<head>里

完整代码示例(以Chrome为例):

from selenium import webdriver

# 启动Chrome浏览器(需确保ChromeDriver已配置好)
driver = webdriver.Chrome()
driver.get("https://example.com")  # 替换成你的目标页面URL

# 自定义样式字符串,注意保持格式
custom_css = """
body {
  background-image: url('example_img.jpg');
  background-repeat: no-repeat;
}
"""

# 执行JS插入样式
driver.execute_script("""
// 创建style元素
const styleTag = document.createElement('style');
// 注入样式内容
styleTag.textContent = arguments[0];
// 添加到页面头部
document.head.appendChild(styleTag);
""", custom_css)

# 这里可以继续其他操作,比如验证效果
input("按回车键关闭浏览器...")
driver.quit()

注意事项

  • 图片路径问题:如果是本地图片,建议使用绝对路径(比如url('C:/images/example_img.jpg')),或者将图片转换成Base64编码嵌入,避免路径问题;网络图片需确保URL可正常访问
  • 如果页面没有<head>标签,可以把document.head.appendChild(styleTag)改成document.body.appendChild(styleTag)或者document.documentElement.appendChild(styleTag),一样能生效

内容的提问来源于stack exchange,提问作者NaWeeD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:10:19