jsoup 获取指定页面的所有链接(需后续完善)

本文介绍了一个简单的Java程序,该程序利用Jsoup库从指定URL(例如百度首页)抓取所有超链接。通过连接到网站并解析HTML文档,程序能够遍历并打印出页面上所有的<a>标签及其href属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java代码如下:

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ListLinks {

	public static void main(String[] args) throws IOException {
		String url = "http://www.baidu.com/";

		Document doc = Jsoup.connect(url).get();
		Elements links = doc.select("a[href]");
		for (Element link : links) {
			System.out.println(link.attr("href"));
		}

	}

}

执行结果如下:

转载于:https://www.cnblogs.com/minisculestep/p/4978880.html

public class Day03 { public static String listUrl="http://ebid.scpcdc.com.cn/hwgg/index.jhtml"; public static Pattern p = Pattern.compile("(\\d{4})(年|/|-|\\.)(\\d{1,2})(月|/|-|\\.)(\\d{1,2})"); public static void main(String[] args) throws Exception { getLists(); } static int pageTotal = 1; static int currPage = 1; private static void getLists() throws Exception { while (currPage <= pageTotal) { String listHtml = doGet(listUrl); //拿到总页数 if (currPage == 1) { // Pattern pagePattern = Pattern.compile(" createPageHTML('page-div',174,1,0,'jhtml')"); // 从 <a href="index_174.jhtml">尾页</a> 中提取 Pattern pagePattern = Pattern.compile("href=\"index_(\\d+)\\.jhtml\"[^>]*>尾页<"); Matcher pagem = pagePattern.matcher(listHtml); if (pagem.find()) { pageTotal = Integer.parseInt(pagem.group(1)); } Document document = Jsoup.parse(listHtml); Elements conTags = document.select("li[class=PaddingLR15] "); ArrayList<String> all = new ArrayList<String>(); if (conTags != null) { //获取并解析所有a标签内连接 for (Element conTag : conTags) { //拿到详情链接 String detailUrl = conTag.select("a").attr("href"); //拿到标题跟日期 String title = conTag.select("a").text(); String date = conTag.select("span.Right").text(); Matcher m = p.matcher(date); if (m.find()) { String month = m.group(3).length() == 2 ? m.group(3) : "0" + m.group(3); String day = m.group(5).length() == 2 ? m.group(5) : "0" + m.group(5); date = m.group(1) + "-" + month + "-" + day; } //详情页面处理 String detailContent = doGet(detailUrl); Document detailDocument = Jsoup.parse(detailContent); Element div = detailDocument.select("div[class=WordSection1]").first(); System.out.println(div); String data = "标题: " + title + "\n链接: " + detailUrl + "\n日期: " + date + "\n详情: " + div.toString() + "\n"; all.add(data); } } } else { System.out.println("列表第" + currPage + "页为空"); } // System.out.println(all); currPage = currPage + 1; listUrl = listUrl.replace("index", "index_" + currPage); } }这段代码有问题吗?
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值