【问题标题】:Extracting all Colors from Style of Span Class in web page using Python使用 Python 从网页中 Span 类的样式中提取所有颜色
【发布时间】:2018-10-08 17:10:49
【问题描述】:

这是我当前的代码,我正在尝试从 span 类中的样式中导入所有“背景色 rgb 和值”。来自下面的站点

https://www.asianpaints.com/colour/colour-catalogue.html

screenshot of page html

import requests
from bs4 import BeautifulSoup as bs
import os

URL = "https://www.asianpaints.com/colour/colour-catalogue.html"
r = requests.get(URL)

collec = bs(r.content, 'lxml')

color= collec.find_all(class_='color-box3')

print(color)

【问题讨论】:

  • 您的代码当前打印什么,与您想要的有什么不同?

标签: python web-scraping beautifulsoup


【解决方案1】:

RGB 值都是使用 Javascript 完成的,Python 或 BeautifulSoup 不会处理这就是为什么在返回的 HTML 中看不到所需信息的原因。

另一种更简单的方法是发现网页发出的请求,以获取 JSON 响应形式的颜色列表。然后可以使用json() requests 函数轻松地将数据转换为 Python 字典,然后作为 Python 字典进行访问:

import requests

URL = "https://www.asianpaints.com/content/ap/en/home/colour/colour-catalogue/jcr:content/oneColumnParsys/colourcatalog.colourfamily.json"
data = requests.get(URL).json()

for shade in data['shades']:
    name = shade['shadeName']
    rgb = f"({shade['shadeR']}, {shade['shadeG']}, {shade['shadeB']})"
    print(f"{name} - {rgb}")

为您提供以下色调:

Raven Song - (64, 64, 64)
Platinum Blue - (56, 61, 103)
Black Currant - (65, 64, 67)
Stormy Sky - (58, 65, 80)
Armada - (55, 70, 91)
Navy Blue - (56, 67, 90)
Blue Mountain - (51, 73, 95)
Rich Berry - (77, 67, 72)

在 Python 3.6.6 上测试

【讨论】:

  • 这是解决@Martin Evans 问题的一种非常有效的方法。我有一个问题:为什么 selenium 甚至无法加载 OP 提到的页面?提供加一。谢谢。
  • 我没有尝试过硒。您使用的是哪个后端?
  • 我尝试使用 chrome 驱动程序(如果这就是后端的意思)。谢谢马丁。
  • 在加载页面时使用浏览器的网络工具来发现其他被访问的 url,这非常有用。
猜你喜欢
  • 2019-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 2018-01-26
相关资源
最近更新 更多