首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 呼叫 Python 腳本下載網頁:Runtime.exec 整合範例

     編輯:Java 相關知識

架構概覽

Java 進程透過 Runtime.exec 啟動 Python 解譯器執行爬蟲腳本,Python 負責網路請求與檔案存儲,Java 等待進程結束。

Python 腳本 spider.py

# -*- coding: utf-8 -*-
import sys, os
from urllib import urlopen

class Spider:
    def __init__(self, url_file, download_dir):
        if not os.path.isfile(url_file): sys.exit("URL file not found")
        if not os.path.isdir(download_dir): sys.exit("Download dir not found")
        self.url_file = url_file
        self.download_dir = download_dir

    def download(self):
        with open(self.url_file) as f:
            for line in f:
                line = line.strip()
                if not line: continue
                fname = ''.join(c for c in line if c.isalnum()).replace('html', '') + '.html'
                self.download_one(line, os.path.join(self.download_dir, fname))

    def download_one(self, url, path):
        try:
            data = urlopen(url).read()
            with open(path, 'wb') as fp: fp.write(data)
        except Exception as e:
            print("Failed:", url, e)

if __name__ == '__main__':
    Spider(sys.argv[1], sys.argv[2]).download()

URL 清單 websites.txt

https://blog.csdn.net/fansy1990
https://www.baidu.com

Java 整合程式

public class PyTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        String pyScript = "D:\\spider.py";
        String urlFile = "D:\\websites.txt";
        String outDir = "D:\\tmp";

        ProcessBuilder pb = new ProcessBuilder("python", pyScript, urlFile, outDir);
        pb.environment().put("PATH", "C:\\Python27;" + System.getenv("PATH")); // 確保 python 在 PATH
        Process p = pb.start();
        int exit = p.waitFor();
        System.out.println("Python exit code: " + exit);
    }
}

關鍵注意事項

  • Python 環境:確保 python.exe 在系統 PATH,或在 ProcessBuilder 明確指定完整路徑。
  • 編碼:Python 2 需在檔案頭聲明 # -*- coding: utf-8 -*-;Java 端讀取進程輸出流時需指定正確編碼。
  • 阻塞與超時:waitFor() 會阻塞主線程,長時間任務建議改用非同步讀取輸出流或設定超時(Java 8+ waitFor(timeout, unit))。
  • 錯誤處理:檢查 exitValue() 非零即代表失敗,需讀取 getErrorStream() 獲取錯誤訊息。
  • 替代方案:Jython(純 Java 實現 Python)可直接在 JVM 內執行 Python 碼,避免進程開銷,但僅支援 Python 2.7 語法,且無法使用 C 擴展套件(如 requests、lxml)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved