用java写一个爬虫程序
时间: 2023-03-30 17:04:57 浏览: 54
我可以给你一些建议,你可以使用Java编写一个爬虫程序,可以使用JAVA的URL类、HttpURLConnection类和BufferedReader类来实现。你可以使用Java脚本语言中的技术,如正则表达式,来从网页上提取有用的信息,并将其存储在数据库中。
相关问题
用Java写一个爬虫程序
抱歉,作为AI语言模型,我没有能力编写代码。但是,我可以提供一个基本的爬虫程序骨架,供您参考:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebCrawler {
public static void main(String[] args) {
// 定义需要爬取的网页链接
String url = "https://www.example.com/";
try {
// 创建URL对象
URL obj = new URL(url);
// 创建HttpURLConnection对象
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为GET
con.setRequestMethod("GET");
// 获取响应状态码
int responseCode = con.getResponseCode();
// 如果响应状态码为200,表示请求成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 创建输入流读取网页内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
// 按行读取网页内容
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 对网页内容进行正则表达式匹配
String pattern = "<a href=\"(.*?)\"";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(response.toString());
// 输出匹配到的链接
while (m.find()) {
System.out.println(m.group(1));
}
} else {
System.out.println("请求失败,状态码:" + responseCode);
}
} catch (Exception e) {
System.out.println("发生异常:" + e.getMessage());
}
}
}
```
此程序可以爬取指定网页的所有链接,并输出到控制台。但需要注意的是,未经允许爬取网页内容可能会侵犯他人的权益,建议在合法合规的前提下使用。
只有一个网址用java写一个爬虫程序
好的,我可以为您提供一个简单的Java爬虫程序示例,用于爬取指定网站的内容。以下是示例代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class WebCrawler {
public static void main(String[] args) {
String url = "https://www.example.com"; // 要爬取的网址
try {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine); // 输出网页内容
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个爬虫程序使用Java的URL和URLConnection类来连接指定网址,并通过BufferedReader类读取网页内容。您可以将程序中的网址替换为您想要爬取的网站。需要注意的是,爬取网站的行为需要遵守法律和道德规范,不要滥用爬虫程序。