如何使用Jsoup从网站获取内容
问题描述:
我试图从网站获取数据。使用此代码:如何使用Jsoup从网站获取内容
@WebServlet(description = "get content from teamforge", urlPatterns = { "/JsoupEx" })
public class JsoupEx extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String URL = "http://www.moving.com/real-estate/city-profile/results.asp?Zip=60505";
public JsoupEx() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Document doc = Jsoup.connect(URL).get();
for (Element table : doc.select("table.DataTbl")) {
for (Element row : table.select("tr")) {
Elements tds = row.select("td");
if (tds.size() > 1) {
System.out.println(tds.get(0).text() + ":"
+ tds.get(2).text());
}
}
}
}
}
我正在使用jsoup解析器。运行时,我不会有任何错误,只是没有输出。
请帮忙。
答
用下面的代码
public class Tester {
private static final String URL = "http://www.moving.com/real-estate/city-profile/results.asp?Zip=60505";
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect(URL).get();
System.out.println(doc);
}
}
我得到一个java.net.SocketTimeoutException:读超时。我认为您试图抓取的特殊网址对于Jsoup来说太慢了。在欧洲,我的联系可能会比你慢。但是,您可能想要在AS的日志中检查此异常。
通过超时设置为10秒,我就可以下载并解析文档:
Connection connection = Jsoup.connect(URL);
connection.timeout(10000);
Document doc = connection.get();
System.out.println(doc);
随着你的代码的其余部分,我得到:
人口:78413
人口自1990年以来的变化:53.00%
人口密度:6,897
男:41137
女:37278
.....
答
感谢名单朱利安,我试着用下面的代码,让SocketTimeoutException。和代码是
Connection connection=Jsoup.connect("http://www.moving.com/real-estate/city-
profile/results.asp?Zip=60505");
connection.timeout(10000);
Document doc = connection.get();
System.out.println(doc);
猜猜别人会需要更多的洞察力!如果您没有收到任何错误,请提供信息,比如您如何尝试运行该程序。 – LGAP 2013-02-15 09:10:01
您的程序中的网址不起作用。该页面不包含表格。 – CharliePrynn 2013-02-15 09:10:53
你确定你的servlet正在部署成功吗?检查您的服务器日志是否有错误,并在发现问题时将其包含在您的问题中 – Perception 2013-02-15 09:11:16