【发布时间】:2016-07-30 12:42:22
【问题描述】:
我想从页面源中提取一些 html 数据。这是参考。链接有一个 html 链接视图源:http://www.4icu.org/reviews/index2.htm。请问如何用JAVA只提取大学名称和国家名称。我知道如何在它们之间提取大学名称,但是我怎样才能通过在 class="i" 时扫描表格来加快程序速度,并用 <... alt="美国">
<tr>
<td><a name="UNIVERSITIES-BY-NAME"></a><h2>A-Z list of world Universities and Colleges</h2>
</tr>
<tr>
<td class="i"><a href="/reviews/9107.htm"> A.T. Still University</a></td>
<td width="50" align="right" nowrap>us <img src="/i/bg.gif" class="fl flag-us" alt="United States" /></td>
</tr>
提前致谢。
编辑 按照@11thdimension 所说,这是我的 .java 文件
public class University {
public static void main(String[] args) throws Exception {
System.out.println("Started");
URL url = new URL ("http://www.4icu.org/reviews/index2.htm");
URLConnection spoof = url.openConnection();
// Spoof the connection so we look like a web browser
spoof.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");
String connect = url.toString();
Document doc = Jsoup.connect(connect).get();
Elements cells = doc.select("td.i");
Iterator<Element> iterator = cells.iterator();
while (iterator.hasNext()) {
Element cell = iterator.next();
String university = cell.select("a").text();
String country = cell.nextElementSibling().select("img").attr("alt");
System.out.printf("country : %s, university : %s %n", country, university);
}
}
}
但是,当我运行它时,它给了我以下错误。
Started
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=http://www.4icu.org/reviews/index2.htm
EDIT2 我创建了以下程序来获取 html 站点的标题。
public class Get_Header {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.4icu.org/reviews/index2.htm");
URLConnection connection = url.openConnection();
Map responseMap = connection.getHeaderFields();
for (Iterator iterator = responseMap.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(key + " = ");
List values = (List) responseMap.get(key);
for (int i = 0; i < values.size(); i++) {
Object o = values.get(i);
System.out.println(o + ", ");
}
}
}
}
它返回以下结果。
X-Frame-Options =
SAMEORIGIN,
Transfer-Encoding =
chunked,
null =
HTTP/1.1 403 Forbidden,
CF-RAY =
2ca61c7a769b1980-HKG,
Server =
cloudflare-nginx,
Cache-Control =
max-age=10,
Connection =
keep-alive,
Set-Cookie =
__cfduid=d4f8d740e0ae0dd551be15e031359844d1469853403; expires=Sun, 30-Jul-17 04:36:43 GMT; path=/; domain=.4icu.org; HttpOnly,
Expires =
Sat, 30 Jul 2016 04:36:53 GMT,
Date =
Sat, 30 Jul 2016 04:36:43 GMT,
Content-Type =
text/html; charset=UTF-8,
虽然我可以得到标题,但是我应该如何将EDIT和EDIT2中的代码组合成一个完整的?谢谢。
【问题讨论】:
-
你需要做一次还是重复性的工作?
-
解决方案需要多长时间才能证明搁置问题的合理性?
-
我已编辑问题以缩小我的问题范围。谢谢
-
我也尝试过使用 URL,但站点似乎阻止了脚本下载尝试,这一定是因为它期望的某些标头。如果您从浏览器中复制发送的标头并在连接中指定它们,那么它也应该与 URL 一起使用。