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

Protractor测试中XMLHTTPRequest会话传递及页面内容获取问题

问题2:无需逐个打开页面获取内容的其他方法

1. 使用浏览器上下文的Fetch API(语法更简洁)

在浏览器环境中执行Fetch请求,自动复用当前会话,语法比XHR更简洁:

const cookies = await browser.manage().getCookies();
const cookieStr = cookies.map(c => `${c.name}=${c.value}`).join('; ');

const response = await browser.executeAsyncScript((url, cookie) => {
  const callback = arguments[arguments.length - 1];
  fetch(url, {
    method: 'GET',
    headers: {
      'Cookie': cookie,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
    },
    credentials: 'include'
  }).then(res => res.text()).then(callback);
}, 'https://mybaseURL.com/member/XX001', cookieStr);

console.log(response);

2. 在Node.js环境发起请求

使用Axios等HTTP库,直接复用从Protractor获取的Cookie,无需打开浏览器页面:
首先安装依赖:

npm install axios

然后编写代码:

const axios = require('axios');

// 从Protractor获取当前会话的Cookie
const cookies = await browser.manage().getCookies();
const cookieStr = cookies.map(c => `${c.name}=${c.value}`).join('; ');

try {
  const response = await axios.get('https://mybaseURL.com/member/XX001', {
    headers: {
      'Cookie': cookieStr,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
      'Accept-Language': 'en-US,en;q=0.9'
    },
    maxRedirects: 0 // 禁止自动跳转,便于排查重定向问题
  });
  console.log(response.data);
} catch (error) {
  console.error(error.response?.data || error.message);
}

3. 批量处理所有链接

如果所有链接遵循统一格式(如/member/XXxxx),可以生成完整URL列表,用Promise.all批量发起请求,一次性获取所有页面内容:

// 替换为实际的100个成员ID列表
const memberIds = ['XX001', 'XX002', 'XX003', /* ... */ 'XX100'];
const baseUrl = 'https://mybaseURL.com/member/';

const cookies = await browser.manage().getCookies();
const cookieStr = cookies.map(c => `${c.name}=${c.value}`).join('; ');

// 批量发起请求并等待所有结果
const results = await Promise.all(
  memberIds.map(id => 
    browser.executeAsyncScript((url, cookie) => {
      const callback = arguments[arguments.length - 1];
      fetch(url, {
        headers: { 'Cookie': cookie },
        credentials: 'include'
      }).then(res => res.text()).then(callback);
    }, `${baseUrl}${id}`, cookieStr)
  )
);

// 遍历处理每个页面的内容
results.forEach((content, index) => {
  console.log(`成员 ${memberIds[index]} 的页面内容:`, content);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:49:56