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

如何过滤axios返回的HTML响应,按form类名提取指定value属性值

实现方案

首先你之前代码中直接将response赋值给authToken的写法有误,axios返回的响应实际内容存储在response.data字段中。推荐使用DOM解析的方式提取目标值,稳定性远高于正则匹配,两种常见运行环境的实现代码如下:

浏览器环境

浏览器端可直接使用原生DOMParser解析返回的HTML字符串:

await axios(config)
.then(function (response) {
  const htmlStr = response.data
  // 解析HTML为DOM对象
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlStr, 'text/html')
  // 按规则匹配目标元素
  const targetInput = doc.querySelector('form.edit_checkout input[name="authenticity_token"]')
  const authToken = targetInput ? targetInput.value : ''
  console.log(authToken)  
})
.catch(function (error) {
  console.log(error)
})

Node.js环境

Node.js环境没有原生DOM API,可使用cheerio库完成解析,首先安装依赖:
npm install cheerio

实现代码:

const cheerio = require('cheerio')

await axios(config)
.then(function (response) {
  const htmlStr = response.data
  const $ = cheerio.load(htmlStr)
  // 提取对应value属性
  const authToken = $('form.edit_checkout input[name="authenticity_token"]').attr('value')
  console.log(authToken)
})
.catch(function (error) {
  console.log(error)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:06:03