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

Java 正則表達式提取網頁所有超連結與連結文字範例

     編輯:Java 相關知識

前言

從 HTML 原始碼中解析 <a> 標籤的 href 與連結文字,是網頁爬蟲基礎步驟。本文使用 Pattern/Matcher 示範提取流程,並說明正則局限性與建議改用 HTML 解析器。

程式碼


import java.io.*;
import java.net.URL;
import java.util.regex.*;

public class LinkExtractor {
    public static void main(String[] args) throws IOException {
        String html = fetch("https://www.example.com/");
        // 1. 可選:先截取  區塊
        int bodyStart = html.indexOf("= 0) bodyStart = html.indexOf('>', bodyStart) + 1;
        int bodyEnd = html.indexOf("", bodyStart);
        String body = (bodyStart > 0 && bodyEnd > bodyStart) ? html.substring(bodyStart, bodyEnd) : html;

        // 2. 匹配 ...
        Pattern linkTag = Pattern.compile("]*>(.*?)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
        Matcher m = linkTag.matcher(body);

        while (m.find()) {
            String fullTag = m.group(0);
            String inner = m.group(1);

            // 取 href
            Matcher hrefM = Pattern.compile("href\\s*=\\s*[\"']?([^\"'>\\s]+)", Pattern.CASE_INSENSITIVE).matcher(fullTag);
            String href = hrefM.find() ? hrefM.group(1) : "";

            // 取純文字 (移除內部標籤)
            String text = inner.replaceAll("<[^>]+>", "").trim();

            System.out.printf("連結: %s | 文字: %s%n", href, text);
        }
    }

    static String fetch(String urlStr) throws IOException {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(urlStr).openStream(), "UTF-8"))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) sb.append(line);
            return sb.toString();
        }
    }
}

輸出範例

連結: /about.html | 文字: 關於我們
連結: https://api.example.com | 文字: 開放 API
連結: #contact | 文字: 聯絡我們

正則局限與改進建議

  • HTML 非正則語言,巢狀標籤、屬性換行、單雙引號混用、註解等情況正則難以完美處理。
  • 生產爬蟲建議使用 Jsoup:Document doc = Jsoup.connect(url).get(); doc.select("a[href]").forEach(...)。
  • 若必須用正則,請加上 Pattern.DOTALL 跨行匹配,並針對目標網站調整規則。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved