我正在使用 Selenium 来测试电子商务应用程序。我需要检查在列表页面上选择类别时列出的项目与数据库中的项目是否匹配。因此,我使用 selenium 访问页面并将页面源存储在文本文件中。我稍后使用 HTMLCleaner 和 JSoup 解析此文本文件,以获取我希望使用数据库验证的字段。
但是,我注意到页面上列出的某些产品使用了特殊字符,例如 ™ 、 ® 等,这些字符无法正确存储/检索并显示为问号。
我用来存储页面源代码:
BufferedWriter writer = null;
try
{
writer = new BufferedWriter(new FileWriter(filepath+"/"+filename+".txt"));
writer.write(driver.getPageSource());
}
catch ( IOException e)
{
e.printStackTrace();
}
finally
{
try
{
writer.close( );
}
catch (IOException e)
{
}
}
检索并解析文件
Document htmlFile = Jsoup.parse(fileSavedPreviously,"ISO-8859-1");
TagNode tagNode = new HtmlCleaner().clean(fileSavedPreviously);
try {
org.w3c.dom.Document doc = new DomSerializer(new CleanerProperties())
.createDOM(tagNode);
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
//rest of the parsing....
最佳答案
定义流编写器的编码:
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fullpath), "UTF-8"));
并向解析器提供相同的内容:
Document htmlFile = Jsoup.parse(fileSavedPreviously, "UTF-8");
要获取页面的编码,请在浏览器控制台中执行document.inputEncoding
。
关于java - 在 Java 中存储和解析 HTML 时出现特殊字符和符号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38737648/