java读取网页html乱码,[Java教程]Jsoup获取网页内容(并且解决中文乱码问题)

本文介绍了如何使用Jsoup库从网页抓取内容,并解决中文乱码问题。通过建立HTTP连接,设置请求头和超时时间,然后以GBK编码解析输入流获取Document对象。此外,还展示了如何通过不同方式解析网页元素,如根据ID、标签、类名和属性选取元素。示例代码中包含了错误处理和重试机制。

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

[Java教程]Jsoup获取网页内容(并且解决中文乱码问题)

0 2020-11-23 19:00:44

1. 根据连接地址获取网页内容,解决中文乱码页面内容,请求失败后尝试3次private static Document getPageContent(String urlStr) { for (int i = 1; i <= 3; i++) { try { URL url = new URL(urlStr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 默认就是Get,可以采用post,大小写都行,因为源码里都toUpperCase了。 connection.setRequestMethod("GET"); // 是否允许缓存,默认true。 connection.setUseCaches(Boolean.FALSE); // 是否开启输出输入,如果是post使用true。默认是false // connection.setDoOutput(Boolean.TRUE); // connection.setDoInput(Boolean.TRUE); // 设置请求头信息 connection.addRequestProperty("Connection", "close"); // 设置连接主机超时(单位:毫秒) connection.setConnectTimeout(8000); // 设置从主机读取数据超时(单位:毫秒) connection.setReadTimeout(8000); // 设置Cookie // connection.addRequestProperty("Cookie", "你的Cookies"); // 开始请求 int index = urlStr.indexOf("://") + 3; String baseUri = urlStr.substring(0, index) + url.getHost(); Document doc = Jsoup.parse(connection.getInputStream(), "GBK", baseUri); if (doc != null) { return doc; } Thread.sleep(3 * 1000); continue; } catch (Exception e) { e.printStackTrace(); } } return null; }

2. 解析网页数据,通过多种方式获取页面元素public static void main(String[] args) { String urlStr = "http://test.cn/a.html";// 静态页面链接地址 Document doc = getPageContent(urlStr); if (doc != null) { // 1. 根据id查询元素 Element e1 = doc.getElementById("id"); // 2. 根据标签获取元素 Elements e2 = doc.getElementsByTag("p"); // 3. 根据class获取元素 Element e3 = doc.getElementsByClass("class_p").first(); // 4. 根据属性获取元素 Element e4 = doc.getElementsByAttributeValue("href", "http://test.cn").first(); // 5. 根据查询器获取元素(class 为writing的div下的p) Elements e5 = doc.select("div.writing>p"); Elements es = doc.select("div .writing p"); if (es != null && es.size() > 0) { for (Element p : es) { String pStr = p.text().trim(); System.out.println(pStr); } } } }

转载请保留本文网址:http://www.shaoqun.com/a/492882.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值