我在此处输入之前搜索过其他堆栈,但没有找到类似的内容。 我必须抓取包含类似文本的不同 utf-8 网页
“Oggi è una bellissima giornata”
问题出在字符“è”
我使用 jtidy 和 xpath 查询表达式提取此文本,然后使用
进行转换byte[] content = filteredEncodedString.getBytes("utf-8");
String result = new String(content,"utf-8");
其中filteredEncodedString包含文本“Oggi è una bellissima giornata”。 此过程适用于迄今为止分析的大多数网页,但在某些情况下它不会提取 utf-8 字符串。页面编码始终相同,文本相似。
9 月 14 日编辑
我修改了代码如下以获取 utf-8 编码的页面:
URL url = new URL(currentUrl);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), getEncode()));
String line="";
String domString="";
while((line = in.readLine()) != null) {
domString+=line.toString();
}
byte[] bytes = domString.getBytes("UTF-8");
in.close();
return bytes;
//return text.getBytes();
其中 getEncode() 返回页面编码,在本例中为 utf-8。但我仍然注意到 ì 或 é 读得不正确。 这段代码有问题吗? 再次感谢!
编辑于 10 月 2 日
这段代码似乎可以工作。问题在于我没有发布(对此感到抱歉!)的 Dom 文档创建,并且从上面的方法返回了字节。
最佳答案
事后您无法将字符串“转换”为 utf-8。如果字节被错误地转换为字符,那么您已经丢失了数据。
关于java - utf-8 转换并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12373302/