首页 > 解决方案 > 使用 Jsoup 使用 Java 获取 Google 搜索结果

问题描述

首先我在stackoverflow数据库和谷歌中搜索这个问题。不幸的是我找不到解决方案。

我正在尝试获取关键字的 Google 搜索结果。这是我的代码:

    public static void main(String[] args) throws Exception {


    Document doc;
    try{
        doc = Jsoup.connect("https://www.google.com/search?as_q=&as_epq=%22Yorkshire+Capital%22+&as_oq=fraud+OR+allegations+OR+scam&as_eq=&as_nlo=&as_nhi=&lr=lang_en&cr=countryCA&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=&as_rights=").userAgent("Mozilla").ignoreHttpErrors(true).timeout(0).get();
        Elements links = (Elements) doc.select("li[class=g]");
        for (Element link : links) {
            Elements titles = link.select("h3[class=r]");
            String title = titles.text();

            Elements bodies = link.select("span[class=st]");
            String body = bodies.text();

            System.out.println("Title: "+title);
            System.out.println("Body: "+body+"\n");
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }


}

继承人的错误:https ://prnt.sc/ro4ooi

它说:只能遍历数组或 java.lang.iterable 的实例(在链接处)..

当我删除(元素)时:https ://prnt.sc/ro4pa9

谢谢你。

标签: javajsoup

解决方案


推荐阅读