使用Java中的JSOUP从网站获取特定数据?

时间:2017-05-23 06:35:52

标签: java android jsoup

我是HTML / CSS初学者,所以我对Selector(cssQuery)知之甚少...我想只获得红色矩形中的特定数据,如链接中的图片所示。请帮助我,提前谢谢.......

  

格式:
标题,网址,地点,内容

以下是代码:

public class TestJSOUP {
    public static void main(String[] args) throws Exception{
        Document doc = Jsoup.connect("http://scholarship-positions.com/category/under-graduate-scholarship/").get();

        Elements body = doc.getElementsByTag("a");
        for (Element b : body) {
            System.out.println(b.attr("href"));
            System.out.println(b.text());
        }  
    }        
}

这是图像 - https://i.stack.imgur.com/52Gbb.jpg

1 个答案:

答案 0 :(得分:0)

此网站限制抓取工具。所以你需要像下面那样指定UserAgent

Document doc = Jsoup.connect("http://scholarship-positions.com/category/under-graduate-scholarship/")
                    .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
                    .get();
Elements es = doc.select("article");
for (Element b : es) {
            String title = b.select("a[href], [title]").get(0).text();
            String url = b.select("a[href]").get(0).attr("href");
            String place = b.select("li.custom-fields-ak-organization").get(0).text();
            String content = b.select("section.entry").get(0).text();
            System.out.println(title + url + place + content);
}