[英]Extracting certain text from html file
我想從html文件中提取文本,這些文件位於parapraph(p)和link(a href)標簽之間。我想在沒有 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) {
}
}
}
}
但是沒有用。代碼似乎對我很有用。讀者如何能夠捕獲“p”和“a href”標簽。
當你在一行中有這樣的<p>blah</p>
這樣的問題時就會出現問題。 一個簡單的解決方案是將所有<
to \\n<
- 更改為:
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}
}
}
我還建議使用像@HovercraftFullOfEels這樣的解析器庫。
編輯:我已經更新了代碼,所以它更接近工作版本,但可能會遇到更多問題。
我認為使用庫會更容易。 使用這個http://jsoup.org/ 。 您還可以解析String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.