写一段jsoup爬取网站的代码
时间: 2024-01-17 19:04:29 浏览: 106
好的,以下是使用 jsoup 爬取网站的示例代码:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JsoupExample {
public static void main(String[] args) {
try {
// 需要爬取的网站 URL
String url = "https://www.example.com";
// 使用 jsoup 连接到网站并获取 HTML 文档
Document doc = Jsoup.connect(url).get();
// 获取页面中的所有链接
Elements links = doc.select("a[href]");
// 遍历链接并输出
for (Element link : links) {
System.out.println(link.attr("href"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们使用 jsoup 的 `connect()` 方法连接到指定的网站并获取 HTML 文档。然后,我们使用 `select()` 方法获取页面中所有链接,并使用 `attr()` 方法获取链接的 `href` 属性值。最后,我们遍历所有链接并输出到控制台。
希望能帮到你!
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)