[Python] How to get the background color of a web page using selenium with python

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    Using this code:

    import re

    def rgba_to_hex(rgba_str):
    # Extract the numbers from the rgba string
    match = re.match(r'rgba?\((\d+), (\d+), (\d+)(?:, [\d.]+)?\)', rgba_str)
    if not match:
    return None
    r, g, b = map(int, match.groups()[:3])
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)

    # Example use with Selenium
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    import time

    driver = webdriver.Chrome()
    driver.get("https://www.ft.com")
    time.sleep(3)

    bg_color_rgba = driver.find_element(By.TAG_NAME,
    "body").value_of_css_property("background-color")
    bg_color_hex = rgba_to_hex(bg_color_rgba)

    print("Background color (hex):", bg_color_hex)

    driver.quit()


    I get the Background color (hex): #000000 but inspecting the code of the page shows the background color of the financial times is a peach color: #fff1e5

    Why am I getting black?

    Continue reading...

Compartilhe esta Página