【问题标题】:How to web scrape color palettes from a color palette website with Python?如何使用 Python 从调色板网站上抓取调色板?
【发布时间】:2020-07-31 05:23:45
【问题描述】:

我正在尝试从调色板设计网站上抓取带有 rgb 值的调色板列表。每个调色板的 HTML 代码如下所示:

<div class = "item block shadow">    
  <div class="palette">
       <div class="place c4" style="background-color: rgb(34, 14, 36);">...</div>
       <div class="place c3" style="background-color: rgb(52, 32, 86);">...</div>
       <div class="place c2" style="background-color: rgb(84, 84, 197);">...</div>
       <div class="place c1" style="background-color: rgb(99, 156, 217);">...</div>

当我在 Python 上抓取此信息时,输出未显示“style=...”部分:

[<div class="palette">
<div class="place c4"><a href=""></a><span></span></div>
<div class="place c3"><a href=""></a><span></span></div>
<div class="place c2"><a href=""></a><span></span></div>
<div class="place c1"><a href=""></a><span></span></div>
</div>]

有没有办法提取我正在寻找的信息?提前致谢。

编辑:这是我的代码

import requests
from bs4 import BeautifulSoup

page = requests.get('https://colorhunt.co/palettes/popular')
soup = BeautifulSoup(page.text, 'html.parser')
repo = soup.find(class_="item block shadow")
repo_list = repo.find_all(class_='palette')

【问题讨论】:

  • 发布刮板代码。
  • 发布网站网址
  • 人们几乎每一个网络抓取问题都会问同样的问题。

标签: python web-scraping


【解决方案1】:

这里的问题不是你刮错了部分,而是你在页面加载完成之前刮掉了页面。这个页面是https://colorhunt.co/ btw。

当您运行此命令时page = requests.get('https://colorhunt.co/palettes/popular')。你得到的是一个尚未执行 JS 的原始 HTML 文件。看看你得到的 html 的script 标记。您会看到很多 JS 代码用于渲染元素,尤其是在您尝试获取的 palette 类部分中。因此,所有颜色都不在您的抓取内容中。

解决方案:使用一个库,模拟你从代码中浏览网页,运行网页,等待它完成,完成后,抓取。我学习 JS,所以我的选择是 puppeteer,还有一个 Python 等价物,叫做 pyppeteer,但我认为还有更多这样的库。

希望这个答案会有所帮助,尽管你问这个问题已经一年多了。我遇到了这个问题,在任何地方都找不到合法的答案,所以这可能会节省一些其他人的时间。迟到总比没有好:)

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2021-08-01
    • 2019-03-05
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多