gpt4 book ai didi

java - 解析Google搜索结果错误

转载 作者:行者123 更新时间:2023-12-01 09:29:13 25 4
gpt4 key购买 nike

我引用答案来解析谷歌搜索结果。

How can you search Google Programmatically Java API

但是,当我尝试代码时,出现错误。

我应该如何进行修改?

import java.net.URLDecoder;
import java.net.URLEncoder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements ;

public class JavaApplication22 {
public static void main(String[] args) {
String google = "http://www.google.com/search?q=";
String search = "stackoverflow";
String charset = "UTF-8";
String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change this to your company's name and bot homepage!

Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().select(".g>.r>a");

for (Element link : links) {
String title = link.text();
String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");

if (!url.startsWith("http")) {
continue; // Ads/news/etc.
}



System.out.println("Title: " + title);
System.out.println("URL: " + url);
}
}

}

我想这是因为库很重要。但我尝试了 ctrl +shift+i 。它表明 import 语句中没有任何需要修复的内容。

错误

Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.IOException; must be caught
or declared to be thrown at
javaapplication22.JavaApplication22.main(JavaApplication22.java:32)

我应该如何修改代码才能解析 Google 搜索结果?

最佳答案

请用以下代码替换您的主类:

public static void main(String[] args) throws UnsupportedEncodingException, IOException {

String google = "http://www.google.com/search?q=";

String search = "stackoverflow";

String charset = "UTF-8";

String userAgent = "ExampleBot 1.0 (+http://example.com/bot)"; // Change this to your company's name and bot homepage!

Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().select(".g>.r>a");

for (Element link : links) {
String title = link.text();
String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
url = URLDecoder.decode(url.substring(url.indexOf('=') + 1, url.indexOf('&')), "UTF-8");

if (!url.startsWith("http")) {
continue; // Ads/news/etc.
}
System.out.println("Title: " + title);
System.out.println("URL: " + url);
}
}

关于java - 解析Google搜索结果错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39592009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com