如何让 NodeJS 中的 axios 与来自 Python 的请求一样工作?

问题描述 投票:0回答:1

我尝试通过向 https://toloka.to/login.php 发出 POST 请求并使用所有必要的正文参数来获取必要的 cookie,以供将来作为 toloka.to 网站的注册用户使用。

在Python中它可以正常工作,我得到纯html,我可以在其中检查页面是否包含登录用户的元素,并且在cookie中我可以看到类似的内容:

{'toloka_1218067_tt': '1708023715', 'toloka_1218067_f': 'a%3A0%3A%7B%7D', 'toloka_1218067_uf': '0', 'toloka_1218067_u': 'a%3A0%3A%7B%7D'}

在 NodeJS 中我得到这个:

['toloka_data=a%3A2%3A%7Bs%3A11%3A%22autologinid%22%3Bs%3A0%3A%22%22%3Bs%3A6%3A%22userid%22%3Bi%3A-1%3B%7D; expires=Fri, 14-Feb-2025 19:29:42 GMT; Max-Age=31536000; path=/; secure; httponly',
      'toloka_sid=c4ab745ccad638caadda384685c38e36; path=/; secure; httponly',
      'toloka___lastvisit=1708025382; expires=Fri, 01-Jan-1971 00:00:00 GMT; Max-Age=-1676489382; path=/; secure',
      'toloka___tt=1708025382; expires=Fri, 14-Feb-2025 19:29:42 GMT; Max-Age=31536000; path=/; secure',
      'toloka___f=a%3A0%3A%7B%7D; expires=Fri, 14-Feb-2025 19:29:42 GMT; Max-Age=31536000; path=/; secure',
      'toloka___uf=0; expires=Fri, 14-Feb-2025 19:29:42 GMT; Max-Age=31536000; path=/; secure',
      'toloka___u=a%3A0%3A%7B%7D; expires=Fri, 14-Feb-2025 19:29:42 GMT; Max-Age=31536000; path=/; secure']

我搞乱了所有这些cookie,发现对于未来的任何请求,toloka_sid 就足够了。如果您使用任何浏览器登录,请删除除该浏览器之外的所有 cookie,这样就可以了。但我没有在 Python cookie 中看到 toloka_sid,而且最重要的是,没有它它也能工作,而在 NodeJS 中,所有这些 cookie 都无效,包括 toloka_sid。

我还注意到,在 Python 中,大多数 cookie 看起来类似于“toloka_1218067_tt”,而在 NodeJS 中,它看起来像“toloka___tt”。我尝试像在 Python 中那样对数字进行硬编码,用适当的数字替换第二个下划线,但仍然没有成功。

实际代码在这里:

  • Python
    import requests
    
    session = requests.Session()
    
    login = session.post(
        f"https://toloka.to/login.php",
        {
            "username": "SomeUser",
            "password": "SomePassword",
            "autologin": "on",
            "ssl": "on",
            "login": "Вхід",
        },
    )
    
    print(login.cookies.get_dict())
    
    getDataWithCredential = session.get(
        f"https://toloka.to/tracker.php?nm=frieren"
    )
    
    with open('xd.html', 'w', encoding='utf-8') as file:
        file.write(login.text)
    
    with open('xd2.html', 'w', encoding='utf-8') as file:
        file.write(getDataWithCredential.text)
  • NodeJS
    const formData = new FormData();
    formData.append('username', 'SomeUser');
    formData.append('password', 'SomePassword');
    formData.append('autologin', 'on');
    formData.append('ssl', 'on');
    formData.append('login', 'Логін');
    
    const data = await axios.post('https://toloka.to/login.php', formData, { withCredentials: true });
    const cookies = data.headers['set-cookie'];
    
    console.log(cookies);
    console.log(data.data);
python node.js web-scraping cookies request
1个回答
0
投票

好的,这个node.js 会产生相同的打印输出。 我正在使用

node-fetch
而不是“Axios”库。

在您的具体情况下,由于

node-fetch
提供了预期的输出,因此
Axios
可能具有一些与您预期不同的默认行为或响应处理。

Axios
node-fetch
之间的输出差异可能是由于每个库处理响应和标头的方式造成的。虽然这两个库的目标是提供类似的 HTTP 请求功能,但它们的实现细节可能有所不同。

每个库可能有自己的默认值和行为,例如它如何处理重定向、处理 cookie 或解析响应主体。

node.js 输出

{
  toloka_data: 'a%3A2%3A%7Bs%3A11%3A%22autologinid%22%3Bs%3A0%3A%22%22%3Bs%3A6%3A%22userid%22%3Bi%3A-1%3B%7D',
  toloka_sid: '159a8c7bc0059d2e1fc43b53bcc5ad33',
  toloka___lastvisit: '1708050186',
  toloka___tt: '1708050186',
  toloka___f: 'a%3A0%3A%7B%7D',
  toloka___uf: '0',
  toloka___u: 'a%3A0%3A%7B%7D'
}

Python 输出

{
  'toloka_1218067_tt': '1708049854',
  'toloka_1218067_f': 'a%3A0%3A%7B%7D',
  'toloka_1218067_uf': '0',
  'toloka_1218067_u': 'a%3A0%3A%7B%7D'
}

Node.js 代码

import fetch from 'node-fetch';
import fs from 'fs';

const USER_NAME = 'SomeUser';
const PASSWORD = 'SomePassword';

(async () => {
  try {
    const loginResponse = await fetch('https://toloka.to/login.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: `username=${USER_NAME}&password=${PASSWORD}&autologin=on&ssl=on&login=Вхід`
    });

    const cookies = loginResponse.headers.raw()['set-cookie'];
    const cookieDict = {};

    cookies.forEach(cookie => {
      const [keyValuePair] = cookie.split(';');
      const [key, value] = keyValuePair.split('=');
      cookieDict[key] = value;
    });

    console.log(cookieDict);

    // Write the login response to a file
    const loginData = await loginResponse.text();
    fs.writeFileSync('xd.html', loginData, { encoding: 'utf-8' });

    // Fetch data with credentials
    const getDataWithCredentialResponse = await fetch('https://toloka.to/tracker.php?nm=frieren');

    // Write the data with credentials response to another file
    const dataWithCredential = await getDataWithCredentialResponse.text();
    fs.writeFileSync('xd2.html', dataWithCredential, { encoding: 'utf-8' });

  } catch (error) {
    console.error('Error:', error.message);
  }
})();

xd.html 几乎相似但不相同 左边是Python/右边是node.js 通过 WinMerge 进行比较

xd2.html 也进行比较 左边是Python/右边是node.js

© www.soinside.com 2019 - 2024. All rights reserved.