如何用Python BeautifulSoup匹配当前时间元素并提取其CSS背景色
基于当前时间匹配提取热力图单元格背景色的实现
已完成基础逻辑
- 通过
datetime模块获取系统当前时间,格式化为%H:%M形式的字符串,存储在current_time_hora变量中 - 基于
requests库携带自定义请求头,完成目标页面的内容爬取 - 已可通过BeautifulSoup成功定位到id为
map-responsive的目标表格,获取表格全部内部元素
核心实现目标
根据current_time_hora的取值,精准定位表格内文本与该时间字符串完全匹配的tr/th类元素,提取元素的background-color样式属性值,供后续逻辑调用。
匹配规则示例:若当前时间为19:13,直接定位页面内文本内容为“19:13”的对应元素,获取其背景色样式值,无需遍历全表无关元素。
待实现环节
现有代码仅能输出整段目标表格的元素集合,缺少单元素精准匹配、目标样式提取的步骤。
现有参考代码
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)
补充实现逻辑
- 定位到目标表格后,使用BeautifulSoup的文本匹配能力,筛选出标签名为tr或th、且去除空白后的文本内容严格等于
current_time_hora的元素 - 读取匹配元素的
style属性值,拆分样式字符串,提取其中的background-color对应的属性值 - 增加空值判断,若未匹配到对应时间元素,输出提示避免程序抛出异常
补全后可直接运行的代码片段
if data3.status_code == requests.codes.ok: info = BeautifulSoup(data3.text, 'html.parser') # 定位目标表格 target_table = info.find('table', {'id': 'map-responsive'}) # 匹配对应时间的目标元素 target_node = target_table.find( lambda tag: tag.name in ['tr', 'th'] and tag.get_text(strip=True) == current_time_hora ) if target_node: # 解析style属性中的背景色值 node_style = target_node.get('style', '') bg_color = '' for style_part in node_style.split(';'): if 'background-color' in style_part: bg_color = style_part.split(':', 1)[1].strip() break # 输出提取到的背景色值,可直接在后续逻辑中调用 print(f"时间{current_time_hora}对应的元素背景色为:{bg_color}") else: print(f"表格中未找到与时间{current_time_hora}匹配的元素")
内容的提问来源于stack exchange,提问作者Marcelo Pontes Machado
相关产品推荐
相关产品推荐

