爬取51job和猎聘网的信息,想处理字符集问题(51job为gbk,猎聘为utf-8),
找到两个网站字符集信息都在同一标签下
就想先把网页保存成string,解析一遍获取字符集,然后将网页转换成对应的正确的字符集,最后再转换成统一的字符集utf-8
1.0实现,2次调用entity.utils.tostring方法
closeablehttpresponse httpresponse = httpclient.execute(httpget);
if(httpresponse.getstatusline().getstatuscode() == 200) {
//网站转为string
string get_charset_entity2string = entityutils.tostring(httpresponse.getentity());
//解析
document get_charset_document = jsoup.parse(get_charset_entity2string);
//字符集信息提取,51job和猎聘
string charset = get_charset_document.select("meta[http-equiv=content-type]")
.attr("content").split("=")[1];
system.out.println(charset);
//根据字符集重新编码成正确的
string ori_entity = entityutils.tostring(httpresponse.getentity(),charset);
//转换为统一的utf-8
string entity = new string(ori_entity.getbytes(),"utf-8");
system.out.println(entity);
{
报错
参考 https://blog.csdn.net/qq_23145857/article/details/70213277
发现entityutils流只存在一次,但是有不想一个网页要连接两次,
这难不倒我,直接转换原来保留的string
2.0实现,第二次不使用entityutils
closeablehttpresponse httpresponse = httpclient.execute(httpget);
if(httpresponse.getstatusline().getstatuscode() == 200) {
//网站转为string
string get_charset_entity2string = entityutils.tostring(httpresponse.getentity());
//解析
document get_charset_document = jsoup.parse(get_charset_entity2string);
//字符集信息提取,51job和猎聘
string charset = get_charset_document.select("meta[http-equiv=content-type]")
.attr("content").split("=")[1];
system.out.println(charset);
//根据字符集重新编码成正确的,不用entityutils,直接转get_charset_entity2string
string ori_entity = new string(get_charset_entity2string.getbytes(), charset);
//转换为统一的utf-8
string entity = new string(ori_entity.getbytes(),"utf-8");
system.out.println(entity);
{
输出:
字符集依旧有问题,发现不指定字符集,entityutils.tostring()就用"iso-8859-1"字符集,可我就是不知道字符集
看到参考链接下面的解决办法,眼前一亮,把流直接以位数组保存,都能灵活变换
3.0实现,不使用entityutils.tostring,改用entityutils.tobytearray()
closeablehttpresponse httpresponse = httpclient.execute(httpget);
if(httpresponse.getstatusline().getstatuscode() == 200) {
//网站转换为byte[]
byte[] bytes = entityutils.tobytearray(httpresponse.getentity());
//byte列表转为默认字符集
string get_charset_entity2string = new string(bytes);
//解析
document get_charset_document = jsoup.parse(get_charset_entity2string);
//字符集信息提取,51job和猎聘
string charset = get_charset_document.select("meta[http-equiv=content-type]")
.attr("content").split("=")[1];
system.out.println(charset);
//根据字符集重新编码成正确的
string ori_entity = new string(bytes, charset);
//转换为统一的utf-8
string entity = new string(ori_entity.getbytes(), "utf-8");
system.out.println(entity);
}
对于里面的默认字符集
参考:https://blog.csdn.net/wangxin1949/article/details/78974037
1、如果使用了eclipse,由java文件的编码决定
2、如果没有使用eclipse,则有本地电脑语言环境决定,中国的都是默认gbk编码,
只要没有改变英文的编码,就没有影响,只要能从标签里提取出charset字符集就可以转换成正确的
输出正常
换成猎聘的url再尝试
完美,爬虫的字符集真神奇
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!