如何从网站获取特定数据并事后使用?

我想创建一个函数,它接受一个特定颜色的参数并返回它的 rgb 值。我想从中获取数据的网站是 https://flaviocopes.com/rgb-color-codes/

我在网上查看,我必须使用请求和 BeautifulSoup 之类的模块,我发现它们有点简单,但无法使其正常工作,我的代码是:

def getcolor(color):
    response = requests.get('https://flaviocopes.com/rgb-color-codes/')     soup = bfs(response.text, features="html.parser") 
    print(soup.findAll('td')) 
getcolor(color='red')

我正在关注这个 https://towardsdatascience.com/how-to-web-scrape-with-python-in-4-minutes-bc49186a8460 网络抓取教程,这就是我得到的,如果您从上面的网站看到图表,您将看到带有 rgb 和十六进制值的颜色,并且该函数将打印所有表格数据网站如何仅打印特定颜色的 rgb 值?另外如果你有其他方式让我知道

qzc105 回答:如何从网站获取特定数据并事后使用?

您可以使用 lambda 函数查找具有匹配颜色字符串的 <td> 标签,然后下一个 <td> 标签包含您的十六进制值:

import requests
from bs4 import BeautifulSoup


def getColor(color):
    response = requests.get("https://flaviocopes.com/rgb-color-codes/")
    soup = BeautifulSoup(response.content,"html.parser")
    color = color.lower()
    td = soup.find(lambda tag: tag.name == "td" and color == tag.text.lower())
    if td:
        return td.find_next("td").text


print(getColor(color="red"))

打印:

#FF0000
本文链接:https://www.f2er.com/526.html

大家都在问