java - Java Google 搜索程序不会打印搜索结果
问题描述
下面的程序,它的代码是在这里找到的(虽然我稍微编辑了它以包含一个 try-catch 块),应该执行谷歌搜索并将结果打印到屏幕上:
import java.io.IOException;
import java.util.Scanner;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class GoogleSearchJava
{
public static final String GOOGLE_SEARCH_URL = "https://www.google.com/search";
public static void main(String[] args)
{
//Taking search term input from console
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the search term.");
String searchTerm = scanner.nextLine();
System.out.println("Please enter the number of results. Example: 5 10 20");
int num = scanner.nextInt();
scanner.close();
String searchURL = GOOGLE_SEARCH_URL + "?q="+searchTerm+"&num="+num;
//without proper User-Agent, we will get 403 error
try
{
Document doc = Jsoup.connect(searchURL).userAgent("Mozilla/5.0").get();
//below will print HTML data, save it to a file and open in browser to compare
//System.out.println(doc.html());
//If google search results HTML change the <h3 class="r" to <h3 class="r1"
//we need to change below accordingly
Elements results = doc.select("h3.r > a");
for (Element result : results)
{
String linkHref = result.attr("href");
String linkText = result.text();
System.out.println("Text::" + linkText + ", URL::" + linkHref.substring(6, linkHref.indexOf("&")));
}
}
catch(IOException e)
{
e.getStackTrace();
System.out.println("ERROR");
}
}
}
然而,在询问要显示的结果数量后,程序突然结束:
-------------------< com.mycompany:GoogleSearchJava >-------------------
Building GoogleSearchJava 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- exec-maven-plugin:1.5.0:exec (default-cli) @ GoogleSearchJava ---
Please enter the search term.
hello
Please enter the number of results. Example: 5 10 20
5
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 4.810 s
Finished at: 2021-09-18T00:51:59+02:00
------------------------------------------------------------------------
为什么程序不打印找到的结果?
解决方案
推荐阅读
- python - Python 导入模块与 __init__.py 中的函数共享名称
- static-analysis - 有没有办法配置 cppcheck 并能够为 alloc/dealloc 指定位置参数号
- linux - 对于从网络文件系统安装的文件夹,Python glob 返回空?
- spring - 在 Spring 中发布 resttemplate 不起作用并获得工作
- sql - 在 JPA 实体列名称中管理单个撇号(单引号)
- javascript - 当我尝试执行弹出窗口时,为什么会抛出找不到页面错误?
- reactjs - 服务器上启用的 CORS 仍然收到标头错误
- python - 动态日期范围数据切片
- azure - 在 terraform 中配置网关时的“用于应用服务”参数
- java - 比较数组并删除重复项