Java爬虫Jsoup简易使用
2021/6/12 12:51:00
本文主要是介绍Java爬虫Jsoup简易使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、准备工作
1、下载jsoup工具,如果是maven项目,请在pm.xml中加入以下代码:
jsoup虽然不是一个很强大的爬虫工具,但是它对于网页html文档的各种处理确实是很强大的,同时自身也是个非常好用的爬虫,也许无法去做较大难度的数据的抓取,但我认为它是个非常优良的文档处理助手
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.7.3</version> </dependency>
2、确定所要抓取的网站地址:
这里我以百度数据为例:
搜索 “互联网” 相关数据,
获取如上网页中所显示的信息,
下面就开始编写jsoup爬虫代码;
/** * 准备抓取的目标地址,%E4%BA%92%E8%81%94%E7%BD%91 为utf-8格式的 互联网 */ private static String url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=互联网"; public static void main(String[] args) throws Exception { //链接到目标地址 Connection connect = Jsoup.connect(url); //设置useragent,设置超时时间,并以get请求方式请求服务器 Document document = connect.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").timeout(6000).ignoreContentType(true).get(); Thread.sleep(1000); //获取指定标签的数据 Element elementById = document.getElementById("content_left"); //输出文本数据 System.out.println(elementById.text()); //输出html数据 System.out.println(elementById.html()); }
查询结果如下:
以上方式就是使用jsoup获取文本数据的基本操作,下面我们继续尝试在以上基础上获取页面中所有的图片
/** * 准备抓取的目标地址,%E4%BA%92%E8%81%94%E7%BD%91 为utf-8格式的 互联网 */ private static String url = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=互联网"; public static void main(String[] args) throws Exception { //链接到目标地址 Connection connect = Jsoup.connect(url); //设置useragent,设置超时时间,并以get请求方式请求服务器 Document document = connect.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)").timeout(6000).ignoreContentType(true).get(); Thread.sleep(1000); //获取指定标签的数据 Element elementById = document.getElementById("content_left"); //输出文本数据 //System.out.println(elementById.text()); //输出html数据 //System.out.println(elementById.html()); //获取所有图片链接 Elements imgtag = document.getElementsByTag("img"); List<String> imgurlList = new ArrayList<String>(); for (int i = 0; i < imgtag.size(); i++) { if (StringUtils.isNotEmpty(imgtag.get(i).attr("src"))&&imgtag.get(i).attr("src").startsWith("http")) { System.out.println(imgtag.get(i).attr("src")); } } }
输出如下:
由上可以获取到图片链接,下面就是使用jsoup把图片下载下来了,有兴趣的朋友可以试试用这种方法去抓取淘宝商品图片,会更简单方便
根据图片链接下载图片
/** * 下载图片到指定目录 * * @param filePath 文件路径 * @param imgUrl 图片URL */ public static void downImages(String filePath, String imgUrl) { // 若指定文件夹没有,则先创建 File dir = new File(filePath); if (!dir.exists()) { dir.mkdirs(); } // 截取图片文件名 String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length()); try { // 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号 String urlTail = URLEncoder.encode(fileName, "UTF-8"); // 因此要将加号转化为UTF-8格式的%20 imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 写出的路径 File file = new File(filePath + File.separator + fileName); try { // 获取图片URL URL url = new URL(imgUrl); // 获得连接 URLConnection connection = url.openConnection(); // 设置10秒的相应时间 connection.setConnectTimeout(10 * 1000); // 获得输入流 InputStream in = connection.getInputStream(); // 获得输出流 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); // 构建缓冲区 byte[] buf = new byte[1024]; int size; // 写入到文件 while (-1 != (size = in.read(buf))) { out.write(buf, 0, size); } out.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 预览
有问题欢迎交流与指正,谢谢
这篇关于Java爬虫Jsoup简易使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现