Java 提取 HTML 标题 (title) 的三种方法: XPath, 正则表达式, 字符串操作
在 Java 中,您可以使用 XPath、正则表达式和字符串操作来提取 HTML 中的 title 值。下面是每种方法的示例代码:\n\n使用 XPath:\njava\nimport org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\n\npublic class Main {\n public static void main(String[] args) {\n String html = "<html><head><title>Example Page</title></head><body><h1>Hello World</h1></body></html>";\n \n Document document = Jsoup.parse(html);\n Element titleElement = document.select("title").first();\n String title = titleElement.text();\n \n System.out.println(title);\n }\n}\n\n\n使用正则表达式:\njava\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class Main {\n public static void main(String[] args) {\n String html = "<html><head><title>Example Page</title></head><body><h1>Hello World</h1></body></html>";\n \n Pattern pattern = Pattern.compile("<title>(.*?)</title>");\n Matcher matcher = pattern.matcher(html);\n \n if (matcher.find()) {\n String title = matcher.group(1);\n System.out.println(title);\n }\n }\n}\n\n\n使用字符串操作:\njava\npublic class Main {\n public static void main(String[] args) {\n String html = "<html><head><title>Example Page</title></head><body><h1>Hello World</h1></body></html>";\n \n int startIndex = html.indexOf("<title>") + 7;\n int endIndex = html.indexOf("</title>");\n String title = html.substring(startIndex, endIndex);\n \n System.out.println(title);\n }\n}\n\n\n无论您选择哪种方法,请确保在使用正则表达式或字符串操作时对 HTML 进行适当的处理和错误处理。此外,使用 Jsoup 库可以更方便地解析和处理 HTML。
原文地址: https://www.cveoy.top/t/topic/p1WD 著作权归作者所有。请勿转载和采集!