簡體   English   中英

使用python抓取網頁的所有顏色

[英]Grab all colors of a webpage with python

我想找到一種有效的方法從python的給定page-url中提取某種顏色調色板(列表或其他東西)。 我想要的是采用所有背景顏色,標題顏色和所有其他元素。

我已經在這里看到[ 從圖像URL構建調色板 ]可以從圖像中獲取調色板,但是頁面呢?

用硒與上面的例子混合了嗎? 下面的示例顯示了如何從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.
    http://stackoverflow.com/a/16216866/190597 (Jaime)
    http://stackoverflow.com/a/16840350/190597 (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顏色屬性的列表)。 例:

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()

最終列表將是一個元組列表,其中包含標簽名稱和頁面中每個標簽出現的背景顏色,顏色,邊框顏色和背景圖像列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM