struts2小小项目 经验总结(3) 调用python

  1.  程序呢是这样的,java调用python,把需要爬的网址当作参数传进去,然后python爬取内容,然后压缩,java把这个压缩包下载到客户端。
  2. 遇到个麻烦,就是同学的爬虫程序是使用scrapy框架的,需要进入入口程序的文件夹下才可以运行,所以我使用了bat批处理文件实现(不安全,但是水平有限,只能这么干)。
  3. 然后在使用struts提供的下载功能将打包好的程序下载到客户端。
    1. 实现下载功能,就是把action中返回值的类型设置为流,具体的配置如下
      <action name="downloadAction" class="action.Actions.DownloadPics">
                  <result type="stream">
                      <!--指定返回类型为流-->
                      <param name="inputName">Target</param>
                      <!--指定是哪个方法执行之后的返回值-->
                      <param name="contentDisposition">filename="this is you cat.zip"</param>
                      <!--指定文件的名字-->
                  </result>
              </action>
         public InputStream getTarget() throws Exception
              {
                  File file = new File("/Cat'sEye/downloadFiles/zipFile.zip");
                  CallPython callPython = new CallPython();
                  callPython.execute(getTargetUrl());
                  InputStream in = new FileInputStream(file);
                  return in;
              }
          int execute(String url) {
      
      //         先把上次下载的内容清理干净
               File file = new File("/Cat'sEye/downloadFiles/111");
               if(file.exists()){
                   delDir(file);
               }
      
      //         使用bat文件进入python所在的位置,然后实行python程序
              try {
                  FileWriter writer = new FileWriter("runPython.bat");
                  writer.write("@echo  off");
                  writer.write("\r\n ");
                  writer.write("cd /");
                  writer.write("\r\n");
                  writer.write("cd Cat'sEye\\Cat'sEyePython");
                  writer.write("\r\n");
                  writer.write("python dmzj_start.py" + " " + url);
                  writer.write("\r\n ");
                  writer.write("exit");
                  writer.write("\r\n ");
                  writer.write("@echo   on ");
                  writer.close();
                  Process process =  Runtime.getRuntime().exec("cmd /c start   /wait   runPython.bat");
                  process.waitFor();
                  return 0;
              } catch (Exception e1) {
                  e1.printStackTrace();
              }
              return 1;
          }

猜你喜欢

转载自blog.csdn.net/weixin_39452731/article/details/84888656