【问题标题】:Search for a string in html file using Jsoup使用 Jsoup 在 html 文件中搜索字符串
【发布时间】:2016-10-29 08:51:27
【问题描述】:

谁能帮助我使用 Jsoup 或任何其他方法在 HTML 文件中搜索特定字符串。有内置方法,但它们有助于提取特定标签内的标题或脚本文本,而不是一般的字符串。 在这段代码中,我使用了一种这样的内置方法从 html 页面中提取标题。 但我想搜索一个字符串。

package dynamic_tester;
import java.io.File;
import java.io.IOException;  
import org.jsoup.Jsoup;  
import org.jsoup.nodes.Document;  
public class tester {
    public static void main(String args[])
    {       
Document htmlFile = null;
{
try {
    htmlFile = Jsoup.parse(new File("x.html"), "ISO-8859-1");

}
catch (IOException e)
{
    e.printStackTrace();
}
String title = htmlFile.title();
System.out.println("Title = "+title);
}
}
}

【问题讨论】:

  • 如果你想搜索 String 那为什么不直接使用 String 的 indexOf() 方法呢?
  • 但我没有字符串或文本文件来执行此类操作。我也可以对 HTML 文件执行此操作,因为我认为我不能对 html 文件使用 indexOf() 操作。
  • 可以对 HTML 文件使用 indexOf 操作。它们本质上是纯文本。只需在字符串中读取它并搜索您需要的任何内容。
  • 谢谢@11thdimension,如果我需要任何进一步的帮助,我会试一试并回到这里。

标签: java html jsoup


【解决方案1】:

这是一个示例。它将 HTML 文件作为文本字符串读取,然后对该字符串执行搜索。

package com.example;

import java.io.FileInputStream;
import java.nio.charset.Charset;

public class SearchTest {
    public static void main(String[] args) throws Exception {

        StringBuffer htmlStr = getStringFromFile("test.html", "ISO-8859-1");
        boolean isPresent = htmlStr.indexOf("hello") != -1;

        System.out.println("is Present ? : " + isPresent);
    }

    private static StringBuffer getStringFromFile(String fileName, String charSetOfFile) {
        StringBuffer strBuffer = new StringBuffer();
        try(FileInputStream fis = new FileInputStream(fileName)) {
            byte[] buffer = new byte[10240]; //10K buffer;
            int readLen = -1;

            while( (readLen = fis.read(buffer)) != -1) {
                strBuffer.append( new String(buffer, 0, readLen, Charset.forName(charSetOfFile)));
            }

        } catch(Exception ex) {
            ex.printStackTrace();
            strBuffer = new StringBuffer();
        }

        return strBuffer;
    }
}

【讨论】:

  • 谢谢@11thdimension。虽然按照您之前的评论,我只是用 HTML 文件替换了文本文件,它工作正常。但也感谢您的代码。目前,我正在使用自己的代码。
猜你喜欢
  • 2018-03-30
  • 2019-08-12
  • 2012-02-14
  • 1970-01-01
  • 2011-11-01
  • 1970-01-01
  • 2021-05-02
  • 2021-11-14
相关资源
最近更新 更多