You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup提取tarifaluzhora.es中绿圈时段的时间与价格数据?

提取低价电价时段数据并通过WhatsApp发送

问题背景

需要从tarifaluzhora.es网站提取带有绿色圆圈(对应template-tlh__background-color-high类)的时段时间与价格数据,后续通过whatsapp-web.js发送。目前已通过BeautifulSoup获取到目标div元素,但不知道如何提取核心数据。

已使用的Python代码:

divs = soup.find_all('div', class_ = "col-xs-11 col-lg-5 template-tlh__colors")

for div in divs:
  print(div)
  print(" ")

返回的HTML结构示例:

<div class="col-xs-11 col-lg-5 template-tlh__colors">
<div class="template-tlh__colors--hours">
<div class="template-tlh__colors--hours-info">
<div class="template-tlh__colors--hours-circle template-tlh__background-color-high"> </div>
<span itemprop="description">20:00 - 21:00</span>
</div>
<div class="template-tlh__colors--hours-price template-tlh__color-high">
<span itemprop="price">0.06643
€/kWh</span>
<meta content="EUR" itemprop="priceCurrency"/>
</div>
</div>
</div>

解决方案

1. 提取时间与价格数据(Python)

遍历获取到的div元素,通过itemprop属性定位时间和价格节点,提取并清理文本内容:

from bs4 import BeautifulSoup

# 假设已完成页面请求与soup解析
divs = soup.find_all('div', class_="col-xs-11 col-lg-5 template-tlh__colors")
low_price_data = []

for div in divs:
    # 提取时段时间
    time_element = div.find('span', itemprop='description')
    period = time_element.get_text(strip=True) if time_element else None
    
    # 提取价格(处理原HTML中的换行问题)
    price_element = div.find('span', itemprop='price')
    if price_element:
        # 清理文本并拼接单位
        price = price_element.get_text(strip=True).replace('\n', ' ')
    else:
        price = None
    
    if period and price:
        low_price_data.append({"时段": period, "价格": price})

# 验证提取结果
for item in low_price_data:
    print(f"{item['时段']}: {item['价格']}")

2. 通过whatsapp-web.js发送数据(Node.js)

将提取到的数据整理成易读的消息格式,使用whatsapp-web.js发送给目标联系人:

const { Client, LocalAuth } = require('whatsapp-web.js');

const client = new Client({
    authStrategy: new LocalAuth()
});

client.on('ready', () => {
    console.log('WhatsApp客户端已就绪');
    
    // 替换为实际提取到的数据
    const lowPriceData = [
        {"时段": "20:00 - 21:00", "价格": "0.06643 €/kWh"},
        {"时段": "21:00 - 22:00", "价格": "0.07924 €/kWh"}
    ];
    
    // 构建消息内容
    let message = "今日低价电价时段:\n";
    lowPriceData.forEach(item => {
        message += `- ${item.时段}: ${item.价格}\n`;
    });
    
    // 发送到目标号码(格式:国家代码+手机号,不带+,后缀@c.us)
    const targetNumber = "1234567890";
    client.sendMessage(`${targetNumber}@c.us`, message);
});

client.initialize();

如果需要Python与Node.js联动,可以将Python提取的数据保存为JSON文件,再由Node.js读取发送。


内容的提问来源于stack exchange,提问作者diaverso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:45:02