gpt4 book ai didi

node.js - 抓取 Nodejs

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:39 24 4
gpt4 key购买 nike

我想用 Nodejs 抓取页面“https://www.ukr.net/ua/news/sport.html”。我正在尝试使用“请求”npm 模块发出基本的获取请求,这里是示例:

const inspect = require('eyespect').inspector();
const request = require('request');
const url = 'https://www.ukr.net/news/dat/sport/2/';
const options = {
method: 'get',
json: true,
url: url
};

request(options, (err, res, body) => {
if (err) {
inspect(err, 'error posting json');
return
}
const headers = res.headers;
const statusCode = res.statusCode;
inspect(headers, 'headers');
inspect(statusCode, 'statusCode');
inspect(body, 'body');
});

但在响应正文中我只得到

body: '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN">\n<html>\n<head>\n<META HTTP-EQUIV="expires"
CONTENT="Wed, 26 Feb 1997 08:21:57 GMT">\n<META HTTP-EQUIV=Refresh
CONTENT="10">\n<meta HTTP-EQUIV="Content-type" CONTENT="text/html;
charset=utf-8">\n<title>www.ukr.net</title>\n</head>\n<body>\n
Идет загрузка, подождите .....\n</body>\n</html>'

如果我从 Postman 发出获取请求,我就会得到我所需要的:

enter image description here

请大家帮帮我。

最佳答案

您可能已被机器人防护阻止 - 这可以使用 curl 进行检查。

curl -vL https://www.ukr.net/news/dat/sport/2/

curl 似乎得到了结果,如果curl 正常工作,那么来自 Node 的请求中可能缺少某些内容,解决方案可能是模仿您选择的浏览器。

例如 - 以下是从开发人员工具中获取的类似 Chrome 的请求示例:

enter image description here

为请求派生以下选项:

const options = {
method: 'get',
json: true,
url: url,
gzip: true,
headers: {
"Host": "www.ukr.net",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch, br",
"Accept-Language": "en-US,en;q=0.8"
}
};

关于node.js - 抓取 Nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com