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

如何用Google Apps Script将标题与URL按列写入Google表格

修改后的Google Apps Script代码方案

以下是调整后的代码,实现标题在A列、URL在B列的纵向排列输出:

function jijiPress() {
  let response = UrlFetchApp.fetch("https://jen.jiji.com/jc/eng?g=ind");
  let text = response.getContentText("utf-8");
  let biz_article = Parser.data(text).from('class="textL">').to('</ul>').build();
  let topics = Parser.data(biz_article).from('<a').to('</a>').iterate();
  let dt = new Date();
  let y = dt.getFullYear();
  let m = ("00" + (dt.getMonth()+1)).slice(-2);
  let d = ("00" + (dt.getDate())).slice(-2);
  let h = dt.getHours();
  let mm = dt.getMinutes();
  let filename = `${y}${m}${d}${h}${mm}_jiji_articles`;
  let newsData = [];

  for(let news of topics){
      // 提取新闻URL
      let newsUrl = news.replace(/.*href="/,'').replace(/".*/,'');
      newsUrl = "https://jen.jiji.com/jc/eng?g=ind" + newsUrl;
      // 提取新闻标题并去除空白
      let newsTitle = news.replace(/href[^>]*>/,'').trim();
      // 将标题和URL组合为一行数据存入数组
      newsData.push([newsTitle, newsUrl]);
  }

  let ss = SpreadsheetApp.create(filename);
  // 将二维数组写入表格,每行对应一组标题与URL
  ss.getActiveSheet().getRange(1, 1, newsData.length, 2).setValues(newsData);

  Logger.log(newsData);
  Logger.log("done!");  
}

关键修改说明

  • 重构数据结构:移除原有的Title和URL两个独立数组,改用newsData数组直接存储[标题, URL]的子数组,最终形成[[标题1, URL1], [标题2, URL2], ...]的二维结构,完美匹配表格的纵向行排列需求
  • 修正变量声明:给topics和循环变量news添加let声明,避免隐式全局变量导致的潜在问题
  • 简化代码逻辑:
    • 复用同一个Date实例获取时间,无需重复创建
    • 用模板字符串简化文件名拼接
    • 给标题添加trim()方法,去除提取过程中可能产生的前后空白字符
  • 删除冗余代码:移除原代码中重复的dTitle.push(URL);语句,清理无效逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:35:28