昨天在网上百度看到一个提问:http://zhidao.baidu.com/question/423488719.html?fr=uc_push&push=ql&oldq=1(题目内容是用jsoup抓取这个网站的信息并输出Free一栏中排名上升度大于30的游戏名)
因为刚看了Jsoup,所以就拿过来做了一下,源代码如下(仅供参考,如果有什么不对的地方,欢迎指正)
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class PageParse {
public static void main(String[] args) {
String concreateURL = "http://www.appannie.com/top/iphone/united-states/games/";
Connection c = Jsoup.connect(concreateURL);
try {
// 这里如果直接用c.get()是获取不到Document的,具体原因我说不上来
// 跟踪信息是:java.io.IOException: 503 error loading URL
// http://www.appannie.com/top/iphone/united-states/games/
// 下面这种获取方式可以
Document doc = c.data("query", "Java").userAgent("Chrome")
.cookie("auth", "token").timeout(5000).post();
// 很想只获取css为上升的域,但是完整的css加上去没有效果,就把这一列域全部获得了(需要改进,肯定有更好的方法)
Elements eles = doc.select("td.top_free*");
List<String> nameList = new ArrayList<String>();
for (Element ele : eles) {
String text = ele.select("span").first().text();
if (text.length() > 1 && text.startsWith("▲")) {
if (Integer.parseInt(text.substring(1)) > 30) {
// 在这里.html()和.text()方法获得的内容是一样的
System.out.println(ele.select("a").first().html());
nameList.add(ele.select("a").first().text());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我运行时的结果是:
The Tribez
PipeRoll
Road Warrior Multiplayer Racing - by Top Free Apps and Games
The Oregon Trail: American Settler
Jewels of the Amazon
Zombie Band
Cleopatra's Pyramid
Monster Galaxy: The Zodiac Islands
代码中的nameList存放的是热度大于30的游戏名,在代码中我没有处理这个List,如果有人看到并会改正的话,欢迎指出,最好是给出一个解释,因为写这个也是糊里糊涂的。
参考资料:
- 开源中国站长写的一篇文章:使用Jsoup对HTML文档进行解析和操作
- jsoup的官方网站: http://jsoup.org/(里面的cookbook是了解jsoup的权威的基础资料)