使用 python 抓取网页的所有颜色

Grab all colors of a webpage with python

我想找到一种有效的方法来从给定的 page-url 和 python 中提取某种 color-palette(列表或其他内容)。我想要的是采用所有背景颜色、标题颜色和所有其他元素。

我已经在这里 [Build a color palette from image URL ] 看到可以从图像中提取调色板,但是页面呢?

是否将 selenium 与上面的示例混合在一起。 下面的示例显示了如何从 Google 的搜索中获取前十种颜色。

只需用网络爬虫截取网页,然后处理图像

#!/bin/env python3
from selenium import webdriver
import numpy as np
from PIL import Image

def palette(img):
    """
    Return palette in descending order of frequency
    """
    arr = np.asarray(img)
    palette, index = np.unique(asvoid(arr).ravel(), return_inverse=True)
    palette = palette.view(arr.dtype).reshape(-1, arr.shape[-1])
    count = np.bincount(index)
    order = np.argsort(count)
    return palette[order[::-1]]

def asvoid(arr):
    """View the array as dtype np.void (bytes)
    This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
     (Jaime)
     (Jaime)
    Warning:
    >>> asvoid([-0.]) == asvoid([0.])
    array([False], dtype=bool)
    """
    arr = np.ascontiguousarray(arr)
    return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))


def savePrint(imageFile):
    driver = webdriver.Firefox()
    driver.get("https://google.com.br")    
    driver.get_screenshot_as_file(imageFile)

imageFile = '/tmp/tmp.png'
savePrint(imageFile)
img = Image.open(imageFile, 'r').convert('RGB')
print(palette(img)[:10])

我尝试了以下对我有用的方法:我的想法是使用 selenium 访问页面源,然后我搜索所有以“<”开头的字符串并将它们清理到列表中,方法是删除'<' 从一开始。然后我迭代列表并为每个列表使用 value_of_css_property 并搜索背景颜色、边框颜色、颜色、背景图像。我知道这并不完美,但它可以满足我的需求。不要忘记从标签列表中删除重复项(因为此方法将给出每个标签的所有 css-color 属性的列表)。 示例:

url ="someurl"
options = webdriver.ChromeOptions()
options.headless = False
driver = webdriver.Chrome(options=options)
driver.get(url)
list_tags = []
html_source = driver.page_source
txt = re.findall(r'<[a-zA-Z]+', html_source)
for x in txt:
    list_tags.append(x.replace('<', ''))
list_tags = list(dict.fromkeys(list_tags))
final_list = []

for i in list_tags:
 tag = driver.find_elements_by_tag_name(i)
 tag_back_col = []
 tag_col = []
 tag_img = []
 tag_border = []
 for j in tag:
      back_col = j.value_of_css_property('background-color')
      tag_back_col.append(back_col)
      col = j.value_of_css_property('color')
      tag_col.append(col)
      bord = j.value_of_css_property('border-color')
      tag_border.append(bord)
      img = j.value_of_css_property('background-image')
      tag_img.append(img)
  final_list .append((i, tag_back_col, tag_col, tag_border, tag_img))
driver.close()

最终列表将是一个元组列表,其中包含标签名称以及该标签在页面中每次出现的背景颜色、颜色、边框颜色和背景图像的列表。