本文由我的微信公众号(bruce常)原创首发,
并同步发表到csdn博客,欢迎转载,2016年12月11日。
概述:
本周五,接到一个任务,要使用爬虫技术来获取某点评网站里面关于健身场馆的数据,之前从未接触过爬虫技术,于是就从网上搜了一点学习资料,本篇文章就记录爬虫技术Jsoup技术,爬虫技术听名称很牛叉,其实没什么难点,慢慢的用心学习就会了。
Jsoup介绍:
Jsoup 是一个 Java 的开源HTML解析器,可直接解析某个URL地址、HTML文本内容,Jsoup官网jar包下载地址。
Jsoup主要有以下功能:
1. 从一个URL,文件或字符串中解析HTML
2. 使用DOM或CSS选择器来查找、取出数据
3. 对HTML元素、属性、文本进行操作
4. 清除不受信任的HTML (来防止XSS攻击)
使用Jsoup爬虫技术你需要的能力有:
- 我们是用安卓开发的,首先肯定要有一定的安卓开发能力,会写简单的页面。
- Jsoup中用到了Javascript语言,没有此语言能力在获取数据的时候就比较吃力,这是此爬虫技术的重中之重。
- 查阅文档与解决问题的能力和技巧(有点废话)
上面三条中对于一个安卓开发者来说,最难的就是熟练使用Javascript语言,小编就遇到了这个问题,小编还有一定的javascript基础,系统的学习过此语言,但是在使用中还是很吃力的,问同学、问朋友、问同事,最后还是靠自己来获取自己想要的数据。
爬虫技术没那么难,思路就是这么的简单
- 得到自己想要爬取数据的url.
- 通过Jsoup的jar包中的方法将Html解析成Document,
- 使用Document中的一些列get、first、children等方法获取自己想要的数据,如图片地址、名称、时间。
- 将得到的数据封装成自己的实体类。
- 将实体中的数据在页面加载出来。
实战,获取**点评网站中的场馆数据:
先奉上效果图,没有图不说话:
这就是今天要实现的效果,左边图片是场馆的logo,右边上方是场馆的名称,下边是场馆的地址信息,点击进去可以根据超链接地址跳转新的页面,页面的Url地址小编已经拿到,但可能是因为重定向的问题,webview没有加载出来,有兴趣的可以输入链接地址来验证。
首先:新建一个空的项目.
上面的效果,只要接触过安卓开发的都能写出来,所以不是本篇文章的重点,这里就不过多说明,大家可以使用ListView或者RecyclerView来实现,我这里用ListView。
小编这里是为了加入侧边栏所以使用的是DrawerLayout,但后来没有用到,所以也就没有侧边栏的效果,不过后期如有时间会加上去的,上一页下一页是为了简单的模仿浏览器中的操作,此效果只能显示前9页数据,网页链接中有50页的数据,为什么没有实现呢?
很简单,因为50页的链接地址不是一次性返回的,小编为了方便,只获取了前9页数据的url,毕竟是为了抓取数据显示而已。
其次:主程序设计
- 通过网页得到**点评健身场馆的url地址是:http://www.dianping.com/search/category/2/45
- 抓取数据是一个耗时的操作,需要在一个线程中完成,这里使用 new Thread(runnable).start()方式,在runnable代码中获取场馆的logo、名称、地址如下:
Runnable runnable = new Runnable() {
@Override
public void run() {
Connection conn = Jsoup.connect(url);
// 修改http包中的header,伪装成浏览器进行抓取
conn.header("User-Agent", userAgent);
Document doc = null;
try {
doc = conn.get();
} catch (IOException e) {
e.printStackTrace();
}
//获取场馆的数据
Element elementDiv = doc.getElementById("shop-all-list");
Elements elementsUl = elementDiv.getElementsByTag("ul");
Elements elements = elementsUl.first().getElementsByTag("li");
for (Element element : elements) {
Elements elements1 = element.children();
String targetUrl = elements1.get(0).getElementsByTag("a").attr("href");
String img = elements1.get(0).getElementsByTag("img").first().attr("data-src");
if (img.contains(".jpg")) {
int a = img.indexOf(".jpg");
img = img.substring(0, a + 4);
}
String radiumName = elements1.get(1).child(0).getElementsByTag("h4").text();
String address0 = elements1.get(