作者:threedayman
来源:恒生LIGHT云社区
提到爬虫,大家会下意识得想到使用python进行数据爬取。作为一个java开发者下意识会想通过熟悉得语言去进行爬虫操作。通过介绍jsoup工具我们来了解下 使用java简单数据爬虫。
jsoup是一种java html得解析工具,提供了便利得API用于抓取URLs,通过DOM操作和CSS selectors提取和操作数据。
接下来我们通过jsoup来抓取网页上得简单信息来熟悉下该工具包得使用。
从Web获取和解析HTML文档,并在其中查找数据,可以使用Jsoup.connect(String url) 方法。
Document doc = Jsoup.connect("http://example.com/").get(); String title = doc.title();
connect(String url)方法创建了一个Connection,通过get()获取并解析html文件为Document对象。
比如获取百度热搜数据:
获取目标网页得URL
目标内容存在得Css Selector信息
获取信息处理
代码如下
public class Baidu { public static void main(String[] args) throws IOException { Document doc = Jsoup.connect("https://www.baidu.com/").get(); Elements ele = doc.select("#hotsearch_data"); System.out.println(ele.text()); } }
其中令人头疼得Css Seletor信息可以通过chrome浏览器
选择对应得html标签信息,鼠标右键→Copy→Copy Selector 我们就可以获取到对应标签得Css Selector。
上面代码运行后 输出如下热搜内容
{"hotsearch":[{"pure_title": "中国驻美大使崔天凯发表辞别信","linkurl": "https%3A//www.baidu.com/s%3Fcl%3D3%26tn%3Dbaidutop10%26fr%3Dtop1000%26wd%3D%25E4%25B8%25AD%25E5%259B%25BD%25E9%25A9%25BB%25E7%25BE%258E%25E5%25A4%25A7%25E4%25BD%25BF%25E5%25B4%2594%25E5%25A4%25A9%25E5%2587%25AF%25E5%258F%2591%25E8%25A1%25A8%25E8%25BE%259E%25E5%2588%25AB%25E4%25BF%25A1%26rsv_idx%3D2%26rsv_dl%3Dfyb_n_homepage%26hisfilter%3D1","views": "","isViewed": "","isNew": "","heat_score": "4945980","hotTags": "3"},{"pure_title": "东莞3病例曾同时在麦当劳用餐","linkurl": "https%3A//www.baidu.com/s%3Fcl%3D3%26tn%3Dbaidutop10%26fr%3Dtop1000%26wd%3D%25E4%25B8%259C%25E8%258E%259E3%25E7%2597%2585%25E4%25BE%258B%25E6%259B%25BE%25E5%2590%258C%25E6%2597%25B6%25E5%259C%25A8%25E9%25BA%25A6%25E5%25BD%2593%25E5%258A%25B3%25E7%2594%25A8%25E9%25A4%2590%26rsv_idx%3D2%26rsv_dl%3Dfyb_n_homepage%26hisfilter%3D1","views": "","isViewed": "","isNew": "","heat_score": "4887061","hotTags": "0"},2584%26rsv_idx%3D2%26rsv_dl%3Dfyb_n_homepage%26hisfilter%3D1","views": "","isViewed": "","isNew": "","heat_score": "4317760","hotTags": "1"} (放上来两条)
我们可以根据实际得需求去解析这部分热搜内容。
通过简单得例子让大家对于数据爬取有个感性认识,希望抛砖引玉,大家能够通过实际使用来发挥jsoup强大得功能。如果大家有更好得爬虫工具,欢迎在留言讨论哈。
jsoup更多使用细节请参考官方文档。
maven依赖
<dependency> <!-- jsoup HTML parser library @ https://jsoup.org/ --> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.13.1</version> </dependency>
参考
jsoup官方文档