Java 从html文件中提取特定文本

Java 从html文件中提取特定文本,java,html,parsing,Java,Html,Parsing,我想从放置在paragraph(p)和link(a href)标记之间的html文件中提取文本。我想在不使用java正则表达式和html解析器的情况下这样做 while ((word = reader.readLine()) !=null) { //iterate to the end of the file if(word.contains("<p>")) { //catching p tag while(!word.contains("</p>

我想从放置在paragraph(p)和link(a href)标记之间的html文件中提取文本。我想在不使用java正则表达式和html解析器的情况下这样做

while ((word = reader.readLine()) !=null) { //iterate to the end of the file
    if(word.contains("<p>")) { //catching p tag
        while(!word.contains("</p>") { //iterate to the end of that tag
            try { //start writing
                out.write(word);
            } catch (IOException e) {
            }
        }
    }
}
while((word=reader.readLine())!=null){//迭代到文件末尾
if(word.contains(“”){//p标记
而(!word.contains(“

”){//迭代到该标记的末尾 尝试{//开始写 写出(单词); }捕获(IOE异常){ } } } }

但不起作用。代码对我来说似乎很有效。读者如何理解“p”和“a href”标签。

当您在一行中出现类似这样的问题时,问题就开始了。一个简单的解决方案是更改所有的
我认为使用库将更容易。使用它。您还可以解析字符串1)始终捕获异常-永远不要将该块保留为空,否则谁知道这次尝试会出什么问题。2) 放入println或使用调试器测试while循环中变量的状态。要解决问题,首先必须诊断原因。3) 为了我的钱,我会使用像JSoup这样的HTML解析器来简化我的生活。为什么要用一种几乎总是会被保证是笨拙的解决方案来重新发明轮子?为什么blah

会导致代码出现问题?我不明白。@cane-r如果你的开始和结束标记在同一行,那么这两个条件(
word.contains(”)和
word.contains(

)都是正确的,所以
out.write(word)
永远不会被调用。@cane-r除了这个问题,你需要将
reader.readLine()
放在内部循环的某个地方,否则它会一遍又一遍地写出同一个单词,直到世界末日。@cane-r我编辑了代码,所以在我的回答中你可以看到我的意思。注意:在Java中没有in关键字。foreach循环是:
for(类型项:iterableCollection)
boolean insidePar = false;
while ((line = reader.readLine()) !=null) {
    for(String word in line.replaceAll("<","\n<").split("\n")){
        if(word.contains("<p>")){
            insidePar = true;
        }else if(word.contains("</p>")){
            insidePar = false;
        }
        if(insidePar){ // write the word}
    }
}