1
我试图从使用JSoup的表中提取财务信息。我查看了类似的问题,并能得到他们的例子来工作(这里有两个:使用JSoup提取表数据
Using JSoup To Extract HTML Table Contents)。
我不确定为什么代码在my URL上不起作用。
下面是3个不同的尝试。任何帮助,将不胜感激。
String s = "http://financials.morningstar.com/valuation/price-ratio.html?t=AXP®ion=usa&culture=en-US";
//Attempt 1
try {
Document doc = Jsoup.connect("http://financials.morningstar.com/valuation/price-ratio.html?t=AXP®ion=USA&culture=en_US").get();
for (Element table : doc.select("table#currentValuationTable.r_table1.text2")) {
for (Element row : table.select("tr")) {
Elements tds = row.select("td");
if (tds.size() > 6) {
System.out.println(tds.get(0).text() + ":" + tds.get(1).text());
}
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
// Attempt 2
try {
Document doc = Jsoup.connect(s).get();
for (Element table : doc.select("table#currentValuationTable.r_table1.text2")) {
for (Element row : table.select("tr")) {
Elements tds = row.select("td");
for (int i = 0; i < tds.size(); i++) {
System.out.println(tds.get(i).text());
}
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
//Attempt 3
try {
Document doc = Jsoup.connect(s).get();
Elements tableElements = doc.select("table#currentValuationTable.r_table1.text2");
Elements tableRowElements = tableElements.select(":not(thead) tr");
for (int i = 0; i < tableRowElements.size(); i++) {
Element row = tableRowElements.get(i);
System.out.println("row");
Elements rowItems = row.select("td");
for (int j = 0; j < rowItems.size(); j++) {
System.out.println(rowItems.get(j).text());
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
你的尝试达到/未能达到什么目标? – lfurini
打印'Document'能够从页面读取的内容(使用'System.out.println(doc);')。有些东西告诉我,您的问题可能与您正在查找的HTML内容是由JavaScript通过浏览器动态添加的事实相关,Jsoup无法执行此操作,因为它没有JavaScript支持。在这种情况下,您应该使用更强大的工具,如网络驱动程序(如Selenium)。 – Pshemo
尝试禁用JavaScript并查看您是否可以在浏览器中看到表格... – Pshemo