【问题标题】:How to get the hover button background color of a website using selenium?如何使用 selenium 获取网站的悬停按钮背景颜色?
【发布时间】:2022-01-22 18:24:55
【问题描述】:

您好,我正在使用 python selenium 来获取按钮的一些 css 属性。我还需要悬停背景颜色。 css是这样的:

.overview .add-to-cart-button:hover, .variant-overview .add-to-cart-button:hover {
background-color: #b41733;}

我的代码是这样的:

    from selenium import webdriver 
from selenium.webdriver.support.color import Color
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome(executable_path = ChromeDriverManager().install())
driver.get('https://www.inshoes.gr/andrikes-zones-andrikes-zones-dermatines-diplis-opseos-33000481-kamel-mavro')


background_color = driver.find_element_by_id('addtocartbutton-7531').value_of_css_property('background-color')
text_color = driver.find_element_by_id('addtocartbutton-7531').value_of_css_property('color')
hex_color = Color.from_string(background_color).hex
hex_text_color = Color.from_string(text_color).hex
print(hex_color)
print(hex_text_color)

有人可以帮我吗?

【问题讨论】:

  • print(hex_color)print(hex_text_color) 打印什么?
  • @DebanjanB 按钮的背景颜色和文本颜色。悬停按钮时需要背景颜色

标签: python selenium selenium-webdriver webdriverwait value-of-css-property


【解决方案1】:

要使用Selenium检索WebElement的悬停按钮背景颜色,首先需要Mouse Hovervisibility_of_element_located()诱导WebDriverWait,然后使用value_of_css_property(),您可以使用以下Locator Strategies

代码块:

driver = webdriver.Chrome(service=s, options=options)
driver.get("https://www.inshoes.gr/andrikes-zones-andrikes-zones-dermatines-diplis-opseos-33000481-kamel-mavro")
basket = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input#addtocartbutton-7531")))
ActionChains(driver).move_to_element(basket).click().perform()
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input#addtocartbutton-7531"))).value_of_css_property('background-color'))

控制台输出:

rgba(242, 35, 65, 1)

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

【讨论】:

  • 这会返回按钮的背景颜色,而不是悬停颜色
  • @user15924442 我认为您的问题是关于 悬停背景颜色 和 HTML background-color: #b41733; 以及您的评论 I need the background color when I hover the button。话虽如此,我可能已经给了你所有的提示和细节。
猜你喜欢
  • 2013-06-26
  • 2018-03-14
  • 2013-11-21
  • 2016-08-12
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多