gpt4 book ai didi

javascript - 来自 Request NodeJS 的 body 的正确编码

转载 作者:行者123 更新时间:2023-11-30 21:09:49 25 4
gpt4 key购买 nike

我正在尝试从网页中抓取一些数据,我设法发布了一个请求并获得了正确的数据。问题是我得到类似的东西:

“Kannst du bitte noch einmal ... erzýhlen, wie du wýhrend der Safari einen Lýwen verjagt hast?”

通常 erzählen - während,所以 Ä,Ö,ß,Ü 没有正确显示。

这是我的代码:

var querystring = require('querystring');
var iconv = require('iconv-lite')
var request = require('request');
var fs = require('fs');
var writer = fs.createWriteStream('outputBodyutf8String.html');


var form = {
id:'2974',
opt1:'',
opt2:'30',
ref:'A1',
tid:'157',
tid2:'',
fnum:'2'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'xxxxxx.php',
body: formData,
method: 'POST'
}, function (err, res, body) {
var utf8String = iconv.decode(body,"ISO-8859-1");
console.log(utf8String);
writer.write(utf8String);
});

如何使用正确的字母获取 HTML 正文?

最佳答案

如何找出响应的正确编码?

我去了你试图抓取的网站,发现了这个:

enter image description here

还有另一个字符编码声明:

enter image description here

本网站定义了两种不同的字符编码! 我用哪个?

嗯,这不适用于你。当从本地机器读取 HTML 文件时,元标记中定义的 charsetcontent-type 将用于编码。

由于您正在通过 HTTP 检索此文档,因此文件将根据响应 header 进行编码。

这是我访问该网站后收到的响应 header 。

enter image description here

如您所见,它们没有定义的字符集。它应该位于 Content-Type 属性中。像这样:

enter image description here

由于他们在响应头中没有任何指示的charset,那么,根据这个post , 它应该使用 meta 声明。

但是等等,有两个meta charset 声明。

由于编译器从上到下读取文件,因此应使用第二个声明的 charset

结论:他们使用UTF-8

此外,我认为您不需要转换。我可能错了,但您应该能够访问响应。

request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'xxxxxx.php',
body: formData,
method: 'POST'
}, function (err, res, body) {
console.log(body);
writer.write(body);
});

编辑:我不认为错误在他们一方。我相信它就在你身边。试一试:

删除作者:

var writer = fs.createWriteStream('outputBodyutf8String.html');

request 回调中,将所有内容替换为:

function (err, res, body) {
console.log(body);
fs.writeFile('outputBodyutf8String.html', body, 'utf8', function(error) {
if(error)
console.log('Error Occured', error);
);
}

所有的代码应该是这样的:

var querystring = require('querystring');
var iconv = require('iconv-lite')
var request = require('request');
var fs = require('fs');

var form = {
id:'2974',
opt1:'',
opt2:'30',
ref:'A1',
tid:'157',
tid2:'',
fnum:'2'
};

var formData = querystring.stringify(form);
var contentLength = formData.length;

request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'xxxxxxx.php',
body: formData,
method: 'POST'
}, function (err, res, body) {
console.log(body);
fs.writeFile('outputBodyutf8String.html', body, 'utf8', function(error) {
if(error)
console.log('Error Occured', error);
);
}

关于javascript - 来自 Request NodeJS 的 body 的正确编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46272845/

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