网页是:http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdeqty_pf.htm http://www.hkex.com.hk/eng/market/sec_tradinfo/stockcode/eisdeqty_pf.htm
我想提取所有<tr class="tr_normal">
使用 Jsoup 的元素。
我正在使用的代码是:
Document doc = Jsoup.connect(url).get();
Elements es = doc.getElementsByClass("tr_normal");
System.out.println(es.size());
但尺寸(1350) 小于实际的 (1452)。
我将此页复制到我的计算机上并删除了一些<tr>
元素。然后我运行了相同的代码,它是正确的。看起来元素太多,jsoup 无法读取所有元素?
那么发生了什么事?谢谢!
问题出在内部 Jsoup Http 连接处理。 选择器引擎没有任何问题。 我没有深入研究,但处理 http 连接的专有方法总是存在问题。 我建议将其替换为 HttpClient -http://hc.apache.org/ http://hc.apache.org/。如果您无法添加 http 客户端作为依赖项,您可能需要检查处理 http 连接的 Jsoup 源代码。
问题是 Jsoup.Connection 的默认 maxBodySize。请参考更新后的答案。 *我仍然保留 HttpClient 代码作为示例。
程序的输出
- 从文件加载= 1452
- 从http客户端加载= 1452
- 从 jsoup 连接加载= 1350
-
使用 maxBodySize= 1452 从 jsoup 连接加载
package test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class TestJsoup {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Document doc = Jsoup.parse(loadContentFromClasspath(), "UTF8", "");
Elements es = doc.getElementsByClass("tr_normal");
System.out.println("load from file= " + es.size());
doc = Jsoup.parse(loadContentByHttpClient(), "UTF8", "");
es = doc.getElementsByClass("tr_normal");
System.out.println("load from http client= " + es.size());
String url = "http://www.hkex.com.hk/eng/market/sec_tradinfo"
+ "/stockcode/eisdeqty_pf.htm";
doc = Jsoup.connect(url).get();
es = doc.getElementsByClass("tr_normal");
System.out.println("load from jsoup connect= " + es.size());
int maxBodySize = 2048000;//2MB (default is 1MB) 0 for unlimited size
doc = Jsoup.connect(url).maxBodySize(maxBodySize).get();
es = doc.getElementsByClass("tr_normal");
System.out.println("load from jsoup connect using maxBodySize= " + es.size());
}
public static InputStream loadContentByHttpClient()
throws ClientProtocolException, IOException {
String url = "http://www.hkex.com.hk/eng/market/sec_tradinfo"
+ "/stockcode/eisdeqty_pf.htm";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
return response.getEntity().getContent();
}
public static InputStream loadContentFromClasspath()
throws ClientProtocolException, IOException {
return TestJsoup.class.getClassLoader().getResourceAsStream(
"eisdeqty_pf.htm");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)