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

如何在iOS Scriptable组件中提取Haema血型储备百分比整数值

解决Scriptable组件中Haema血型储备数据提取问题

需求背景

现有一款iOS Scriptable组件,用于显示德国红十字会与瑞士红十字会的血型储备状态,需添加私人血液供应商Haema的储备数据:

  • Haema官网的储备状态通过SVG文件名中的百分比数值体现,示例HTML结构:
<div class="blood-demand">
  <div class="blood-demand--item">
    <img src="/fileadmin/user_upload/Blutspende/Blutampel/Transfusius-50-prozent-haema.svg" width="162" height="300">
    <div class="blood-demand--title">A+</div>
  </div>
  ...
</div>
  • 需要提取各血型对应的百分比整数值,生成格式为[[50,"A+"],[100,"A-"],[75,"0+"],...]的数组,用于后续根据数值生成对应图标:
function getStatusIcon(percentage) {
  if (percentage <= 15) { return "🔥"; }
  else if (percentage <= 25) { return "🩸"; }
  // 其他匹配条件省略
}
  • 尝试用Request加载HTML,结合WebView和document.querySelectorAll未成功,当前返回格式为[["","A+"],[],["","A-"],...],数值为空。

修正后的代码实现

在Scriptable中,需确保正确遍历每个血型项,从img的src属性提取百分比并匹配对应血型标题,以下是可行代码片段:

async function fetchHaemaData() {
  const url = "https://www.haema.de/blutspende/";
  const req = new Request(url);
  const html = await req.loadString();
  
  const webView = new WebView();
  await webView.loadHTML(html);
  
  // 执行JS提取数据,确保img与血型标题一一对应
  const haemaData = await webView.evaluateJavaScript(`
    const items = document.querySelectorAll('.blood-demand--item');
    const result = [];
    items.forEach(item => {
      const img = item.querySelector('img');
      const title = item.querySelector('.blood-demand--title')?.textContent.trim();
      if (img && title) {
        // 正则提取src中的百分比数值
        const match = img.src.match(/Transfusius-(\\d+)-prozent-haema\\.svg/);
        if (match) {
          const percentage = parseInt(match[1], 10);
          result.push([percentage, title]);
        }
      }
    });
    result;
  `);
  
  return haemaData;
}

// 调用测试
const data = await fetchHaemaData();
console.log(data); // 输出格式符合预期:[[50,"A+"],[100,"A-"],...]

关键修正点

  • 遍历.blood-demand--item容器,确保img和血型标题属于同一项,避免匹配错位
  • 用正则表达式/Transfusius-(\d+)-prozent-haema\.svg/精准提取文件名中的百分比数值
  • 添加空值判断,过滤无效项,避免生成空数组元素
  • 将提取到的字符串百分比转为整数类型,适配后续图标生成逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:55:22