网络爬虫异常文件处理

我们在爬取网页数据的时候常常会出现封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 "";
	}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值