java 爬取12306
时间: 2023-11-04 17:56:21 浏览: 164
要在Java中爬取12306网站,你可以使用HttpClient或Jsoup等库来发送HTTP请求并解析响应内容。下面是一个简单的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) {
String url = "https://www.12306.cn/";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println(content);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,访问12306网站可能需要设置一些请求头或使用验证码识别等技术,具体要根据网站的要求进行处理。此外,爬取网站数据时要遵守相关法律法规和网站的使用条款。
阅读全文