【问题标题】:ImportXML "post_name" from an article, having trouble finding proper XPathImportXML "post_name" 从一篇文章中,找不到合适的 XPath
【发布时间】:2021-06-11 09:58:01
【问题描述】:

我一直无法为 Google 表格 ImportXML 找到正确或准确的 Xpath。

相关文章: https://www.digitaltrends.com/news/this-is-what-a-birthday-party-on-the-iss-looks-like/

我正在寻找的结果: 'post_name': 'this-is-what-a-birthday-party-on-the-iss-looks-like'

使用 Chrome Inspect 功能中的“复制完整 XPath 功能,我得到:

/html/head/script[43]/text()

这不适用于 Google 表格的 ImportXML 功能。有人可以指导我如何提取网站的这一部分吗?

编辑:我正在尝试检索这些参数中的任何内容,例如“帖子名称、帖子标题、帖子 ID”。 [查看源代码1

【问题讨论】:

  • 这对您解释您实际想要实现的目标会有所帮助。内容“this-is-what-a-birthday-party-on-the-iss-looks-like”可在此页面的多个位置找到,其中一些可以很好地与 IMPORTXML 函数配合使用。与从脚本内容中挖掘它相比,可能有更简单的选择。
  • edit您的问题并将您的代码添加为minimal reproducible example和输入html。不要链接到页面,该页面可能会改变,使问题成为有争议的问题。另见How to Ask

标签: xpath google-sheets-formula


【解决方案1】:

页面是在客户端使用 javascript 构建的,而不是在服务器端。因此不可能使用 IMPORTXML 函数检索信息。您需要阅读脚本中包含的内容...

function extract(){
  var url='https://www.digitaltrends.com/news/this-is-what-a-birthday-party-on-the-iss-looks-like/'
  var source = UrlFetchApp.fetch(url).getContentText()
  var data = source.split('<script>')
  //Logger.log(data[3]) 
  info = "'post_name" + data[3].split('post_name')[1].split(',')[0]
  Logger.log(info)
}

现在如果你想检索 JSON 中包含的所有信息

function extract(){
  var url='https://www.digitaltrends.com/news/this-is-what-a-birthday-party-on-the-iss-looks-like/'
  var source = UrlFetchApp.fetch(url).getContentText()
  var data = source.split('<script>')
  //Logger.log(data[3])
  info = data[3].replace(/(\t)/gm,"").replace(/(\n)/gm,"").replace(/(')/gm,"\"").replace(/(: )/gm,":")
  info = info.split('({')[1].split(',});}')[0]
  //Logger.log(info)
  var myData = JSON.parse('{' + info + '}')
  getPairs(eval(myData),'myData')
}
function getPairs(obj,id) {
  const regex = new RegExp('[^0-9]+');
  const fullPath = true
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  for (let p in obj) {
    var newid = (regex.test(p)) ? id + '.' + p : id + '[' + p + ']';
    if (obj[p]!=null){
      if (typeof obj[p] != 'object' && typeof obj[p] != 'function'){
        sheet.appendRow([fullPath?newid:p, obj[p]]);
      }
      if (typeof obj[p] == 'object') {
        getPairs( obj[p], newid );
      }
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    相关资源
    最近更新 更多