hobbyiscoding
hobbyiscoding

Reputation: 41

How to get specific data from website and use it afterhand?

I want to make a function that takes a parameter of a specific color and returns it's rgb value. The website, from that I want to take the data is https://flaviocopes.com/rgb-color-codes/

I looked online and I have to use modules like requests and BeautifulSoup which I found a bit straightforward but couldn't get it to work my code is:

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

I was following this https://towardsdatascience.com/how-to-web-scrape-with-python-in-4-minutes-bc49186a8460 web scraping tutorial and this is what I got, if you saw the chart from the website above you will see colors with rgb and hex values and the function prints all the table data in the website how can i get to print only the rgb value for the specific color? also if you have another way let me know

Upvotes: 1

Views: 45

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use lambda function to find <td> tag with matching color string and then next <td> tag contains your hex value:

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

Prints:

#FF0000

Upvotes: 1

Related Questions