Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中查找HTML代码中的字符串_Java_Html_File Io_Web - Fatal编程技术网

在Java中查找HTML代码中的字符串

在Java中查找HTML代码中的字符串,java,html,file-io,web,Java,Html,File Io,Web,我想尽快在网页的HTML中找到一段文本,我认为我的程序是最糟糕的,但是你有什么建议吗 我的代码如下: public static void main(String[] args) throws Exception { URL url = new URL("http://stackoverflow.com/"); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()))

我想尽快在网页的HTML中找到一段文本,我认为我的程序是最糟糕的,但是你有什么建议吗

我的代码如下:

public static void main(String[] args) throws Exception 
{
    URL url = new URL("http://stackoverflow.com/");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(url.openStream()));

    String isPresent = "img";
    boolean on = false;

    String inputLine;
    while ((inputLine = in.readLine()) != null) 
    { 
         if(inputLine.contains(isPresent)) on = true;   //This takes a lot!!
    } 
 }

由于网页有很多行HTML代码,而且我对HTML几乎没有经验,所以执行
if(inputLine.contains(isPresent))
行有时需要很多秒。你认为在时间方面有没有更有效的方法来改善这一点?谢谢。

一旦“开”设置为“真”

若要执行此操作,请更改您的while状态

while ((inputLine = in.readLine()) != null && !on) 

如果你的意思是尝试。通过这种方式,您可以检查任何标签、发生次数等。。失去了可能性

Document doc = Jsoup.connect("http://stackoverflow.com/").get();
boolean on = false;
if(doc.select("img").size() > 0){
    on = true;
} 

您可以使用java库来解析XML和HTML文档,如,或。在将JSoup二进制文件添加到类路径后,尝试下面的代码

Document doc = Jsoup.connect("http://stackoverflow.com/").get();
String docContent=doc.text();
if(docContent.contains("searchedText"))
     on = true;

我无法想象这段
inputLine.contains(isPresent)
代码花费了很多秒。你是怎么发现的?我会说这是网络延迟,试着区分读取流和查看字符串
isPresent
,您可以看到需要花费很多秒的时间。当你找到关键词时,也要打破循环。是的,这可以正常工作。你能想象为什么这个简单的代码有时会运行这样的异常吗?“线程中的异常”main“java.util.zip.ZipException:Corrupt GZIP trailer”我在代码中使用了nor文件和GZ库。那太好笑了。有时它工作得很好,问题是Jsoup中的文档类给出的。我应该更仔细地调查。