我编写了一个测试网络爬虫类来尝试搜索 Google,如下所示:
public class WebCrawler {
String query;
public WebCrawler(String search)
{
query = search;
}
public void connect()
{
HttpURLConnection connection = null;
try
{
String url = "http://www.google.com/search?q=" + query;
URL search = new URL(url);
connection = (HttpURLConnection)search.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.connect();
BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while((line = read.readLine())!=null)
{
System.out.println(line);
}
read.close();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(ProtocolException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
connection.disconnect();
}
}
}
当我尝试使用测试查询“test”运行它时,我收到 HTTP 响应 403 错误 - 我错过了什么?这是我第一次使用 Java 进行任何网络工作。
最佳答案
403 ==禁止,这是有道理的,因为你是一个机器人,试图访问谷歌的一部分,而他们不希望机器人访问。 Google's robots.txt非常明确地指出您不应该抓取/search。
Google 提供了 search API每天允许 100 个查询。他们提供libraries以及如何在大多数语言(包括 Java)中与其交互的示例。不仅如此,您还必须付费。
关于java - 当程序尝试启动与 Google 的连接时出现 HTTP 响应 403?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17842987/