我想制作一个解析html页面并选择有用信息并显示它的程序。我通过打开一个流然后逐行搜索这个适当的内容来做到这一点,但这是一个耗时的过程。所以我决定把它当作一个xml然后使用xpath来做。我通过在我的系统上创建一个 xml 文件并从流中加载内容来做到这一点,我得到了空白错误,然后我决定将打开的文档定向为
doc = (Document) builder.parse(inputStream);
但同样的错误仍然存在。在这里询问后,有人建议我使用 jSoup 进行 html 解析,现在当我执行以下代码时:
Document doc= Jsoup.connect(url).get();
我读到超时。当用 python 制作相同的程序并使用简单的策略(如使用字符串的 find 方法和搜索)时,我显示的内容太快了。如何让它在java中快速运行?
完整代码:
import java.io.*;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Parser {
public static void main(String[] args) {
Validate.isTrue(true, "usage: supply url to fetch");
try{
String url="http://www.spoj.com/ranks/PRIME1/";
Document doc= Jsoup.connect(url).get();
Elements es=doc.getElementsByAttributeValue("class","lightrow");
System.out.println(es.get(0).child(0).text());
}catch(Exception e){e.printStackTrace();}
}
}
例外:
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:412)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:393)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:159)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:148)
at Parser.main(Parser.java:12)