要使用Java編寫爬蟲來爬取頁面內容,可以按照以下步驟進行操作:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
URL url = new URL("http://example.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
完整的代碼示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class WebCrawler {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
System.out.println(content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
這樣就可以使用Java爬蟲來爬取網頁內容了。請注意,爬取網頁內容時需要遵守網站的規定和法律法規,不要進行惡意爬取和侵犯他人權益的行為。