首页 > 解决方案 > 如何获取特定字符串并返回他的 css 背景颜色

问题描述

我正在尝试抓取一个包含基于时间的“热图”的网站。

我在 python 中有一个代码,可以获取当前时间并将其转换为变量。

我有我的代码来抓取这个网站。

我正在尝试根据当前时间提取 div tr th 的背景颜色。

例如,假设现在是 19:13 点

我想返回包含字符串 19:13 的 div的元素背景颜色,然后在我的代码的另一部分中使用此信息。

使用下面的代码,我可以获得表 id 'map-responsive' 中包含的所有元素,如何正确获取基于变量 current_time_hora 的信息

谢谢。

from bs4 import BeautifulSoup
from datetime import datetime
import requests

now = datetime.now()
current_time_hora = now.strftime("%H:%M")
print("Current Time - Hora =", current_time_hora)



headers = requests.utils.default_headers()
headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'})
data3 = requests.get('http://www.tradertimerzone.com.br/web/index.php?r=operation%2Fmaps&model=5-15', headers=headers)


if data3.status_code == requests.codes.ok:
    info = BeautifulSoup(data3.text, 'html.parser')
        
    encontraHorarios2 = ((info.findAll('table', {'id': 'map-responsive'})))
    
    
    print(encontraHorarios2)

标签: pythonweb-scrapingbeautifulsoup

解决方案


import requests
from bs4 import BeautifulSoup
import time

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0",
}

params = {
    "r": "operation/maps",
    "model": "5-15"
}


def main(url, now):
    with requests.Session() as req:
        req.headers.update(headers)
        req.params = params

        req.head(url)
        r = req.get(url)
        soup = BeautifulSoup(r.text, 'lxml')
        target = soup.select_one(
            f'th:-soup-contains("{now}")')['style']
        print(target)


if __name__ == "__main__":
    now = time.strftime('%H:%M')
    print(f"Current Time: {now}")
    main('http://www.tradertimerzone.com.br/web/index.php', now)

输出:

Current Time: 01:42
;background:#00B050

推荐阅读