在抓取俄罗斯网站时存在垃圾字符

时间:2015-03-18 14:31:05

标签: java linux encoding web-crawler cyrillic

我正在尝试在Linux中抓取一个俄罗斯网站,但输出似乎是垃圾字符。 该网站采用UTF-8编码,在阅读时我将编码设置为UTF-8。然而,这似乎并没有解决问题。 我该怎么做才能读到它?

public class Crawl {   
    @SuppressWarnings("unused")
    public static void main(String[] args) {

    URL my_url = new URL("http://www.fmsmoscow.ru/docs/migration_registration/registration.html");
    BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream(),"UTF-8"));
    while (null != (strTemp = br.readLine())){
    System.out.println(strTemp);
        }
    }   
}

以上是相同的代码。 我将代码导出为jar并将其添加到Linux服务器中。 然后我执行它以获取Linux控制台中的输出。

1 个答案:

答案 0 :(得分:0)

通常,您还可以存储内容二进制文件(按原样),然后查看出错的位置。在程序员的编辑器中说,如JEdit或NotePad ++,可以切换编码。它可能会在使用原生Windows-1251的HTML注释中滑落。 也许剥离HTML评论有帮助。

对于容错解码,错误报告,需要CharsetDecoder

CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); // ISO_8859_1
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(my_url.openStream(), decoder);

: 请参阅REPLACE,REPORT上的javadoc。如果你想要更多,那么方法就不同了。您需要读取输入,将字节放在ByteBuffer中,然后

CoderResult result = decoder(byteBuffer, charBuffer, true /*EOF*/);

要从UTF-8中挑选西里尔文序列,可以检查UTF-8序列的有效性:

  • 0xxxxxxx
  • 110xxxxx 10xxxxxx
  • 1110xxxx 10xxxxxx 10xxxxxx
  • ...

因此(未经测试):

void patchMixOfUtf8AndCp1251(byte[] bytes, StringBuilder sb) {
    boolean priorWrongUtf8 = false;
    for (int i = 0; i < bytes.length; ++i) {
        byte b = bytes[i];
        if (b >= 0) {
            sb.appendCodePoint((int)b);
            priorWrongUtf8 = false;
        } else {
            int n = highBits(b); // Also # bytes in sequence
            boolean isUTF8 = !priorWrongUtf8
                    && 1 < n && n <= 6
                    && i + n <= bytes.length;
            if (isUTF8) {
                for (int j = 1; j < i + n; ++j) {
                     if (highBits(bytes[j]) != 1) {
                         isUTF8 = false;
                         break;
                     }
                }
            }
            if (isUTF8) {
                sb.append(new String(bytes, i, i + n, StandardCharsets.UTF_8));
                i += n - 1;
            } else {
                // UTF-8 Continuation char must be Cp1252.
                sb.append(new String(bytes, i, i + 1, "Windows-1251"));
            }
            priorWrongUtf8 = !isUTF8;
        }
    }
}

private int highBits(byte b) {
    int n = 0;
    while (n < 8 && ((1 << (7 - n)) & b) != 0) {
        ++n;
    }
    return n;
}

由于西里尔语不太可能立即连接到UTF-8,因此使用状态priorWrongUtf8

相关问题