java爬虫工具类代码示例
时间: 2023-08-23 07:08:22 浏览: 56
以下是一个简单的 Java 爬虫工具类示例代码:
```
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebCrawler {
public static void main(String[] args) throws IOException {
String url = "http://www.example.com";
String pattern = "<a href=\"(.*?)\">";
String html = getHtml(url);
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(html);
while (m.find()) {
String link = m.group(1);
if (link.startsWith("http")) {
System.out.println(link);
} else {
System.out.println(url + link);
}
}
}
public static String getHtml(String url) throws IOException {
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
Scanner scanner = new Scanner(conn.getInputStream(), "UTF-8");
scanner.useDelimiter("\\A");
String html = scanner.next();
scanner.close();
return html;
}
}
```
该代码使用正则表达式来匹配 HTML 中的链接,并输出到控制台。它还使用 HttpURLConnection 类从指定 URL 获取 HTML。注意,这仅仅是一个简单的示例,实际上的爬虫需要更多的代码来处理异常、存储数据,以及其他的任务。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)