您的位置:首页 > 理论基础 > 计算机网络

网络爬虫异常文件处理

2016-12-12 12:02 225 查看
我们在爬取网页数据的时候常常会出现封IP的情况,导致数据下载不完整,成为脏数据,在清洗数据的时候,我们可以先对下载的异常文件进行单独分类,最后在读取异常文件中的源网址,重新下载。在采集数据的时候注意文件保存的格式具体如下图:<!--源网址-->+网页数据内容



下图就是在清洗的时候整理处理的异常文件



具体代码如下:

private void downloadDragGmp(HttpCall httpCall) {
File file = new File("G:/fileRecord/药品GMP认证");
File files[] = file.listFiles();// 获取目录下的所有文件
HttpCallObj httpRes = null;
for (File f : files) {
String crawlWebsite = HtmlUtil.readWebsite(f.getAbsolutePath(), "UTF-8");// 获取源网址
if (crawlWebsite != null) {
// 如果成功取出源网址,就把目标文件给剪切到其他目录(最好不要删除)
String targetPath = WebConstant.cfdaSaveHtmlDirCopy + "/" + "药品GMP认证";
FileUtil.cutGeneralFile(f.getAbsolutePath(), targetPath);
}
try {
httpRes = httpCall.getResponse(crawlWebsite, "POST");
String pageContent = new String(httpRes.getContent(), "UTF-8");
String savePath = generateSavaPath("药品GMP认证");
String fileName = f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\") + 1);
HtmlUtil.saveHtmlFile(savePath + fileName, pageContent, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}

}
}
读取源网址如下

public static String readWebsite(String filePath, String charset) {
File f = new File(filePath);
FileInputStream fis = null;
InputStreamReader isr = null;

try {
fis = new FileInputStream(f); // 读取原文件
if (StrUtil.isBlank(charset)) {
isr = new InputStreamReader(fis);
} else {
isr = new InputStreamReader(fis, charset);
}
BufferedReader br = new BufferedReader(isr);
String website = br.readLine();
int beginIndex = website.indexOf("<!--");
int endIndex = website.indexOf("-->");
if (beginIndex != -1)
website = website.substring(beginIndex + 4, endIndex).trim();
return website;
} catch (Exception e) {
LOG.error(e);
} finally {
try {
if (isr != null) {
isr.close();
isr = null;
}
} catch (Exception e) {
} finally {
try {
if (fis != null) {
fis.close();
fis = null;
}
} catch (Exception e) {
}
}
}
return "";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络爬虫
相关文章推荐