写过不少个爬虫小程序了,以前几回主要用C# + Html Agility Pack来完成工做。因为.NET BCL只提供了"底层"的HttpWebRequest和"中层"的WebClient,故对HTTP操做仍是须要编写不少代码的。加上编写C#须要使用Visual Studio这个很"重"的工具,开发效率长期以来处于一种低下的状态。html
最近项目里面接触到了一种神奇的语言Groovy -- 一种全面兼容Java语言且提供了大量额外语法功能的动态语言。加上网络上有开源的Jsoup项目 -- 一个轻量级的使用CSS选择器来解析HTML内容的类库,这样的组合编写爬虫简直如沐春风。前端
抓cnblogs首页新闻标题的脚本json
Jsoup.connect("http://cnblogs.com").get().select("#post_list > div > div.post_item_body > h3 > a").each { println it.text() }
output小程序
抓cnblogs首页新闻详细信息浏览器
Jsoup.connect("http://cnblogs.com").get().select("#post_list > div").take(5).each {
def url = it.select("> div.post_item_body > h3 > a").attr("href")
def title = it.select("> div.post_item_body > h3 > a").text()
def description = it.select("> div.post_item_body > p").text()
def author = it.select("> div.post_item_body > div > a").text()
def comments = it.select("> div.post_item_body > div > span.article_comment > a").text()
def view = it.select("> div.post_item_body > div > span.article_view > a").text()网络
println ""
println "新闻: $title"
println "连接: $url"
println "描述: $description"
println "做者: $author, 评论: $comments, 阅读: $view"
}编辑器
output工具
怎么样,很方即是吧。是否是找到一种编写前端JavaScript和jQuery代码的感受,那就对了!post
这里说一个窍门,编写CSS选择器的时候能够借助Google Chrome浏览器的开发工具,如图:开发工具
再来看看Groovy是如何快速处理JSON和XML的。一句话:方便到家。
抓cnblogs的feeds
new XmlSlurper().parse("http://feed.cnblogs.com/blog/sitehome/rss").with { xml ->
def title = xml.title.text()
def subtitle = xml.subtitle.text()
def updated = xml.updated.text()
println "feeds"
println "title -> $title"
println "subtitle -> $subtitle"
println "updated -> $updated"
def entryList = xml.entry.take(3).collect {
def id = it.id.text()
def subject = it.title.text()
def summary = it.summary.text()
def author = it.author.name.text()
def published = it.published.text()
[id, subject, summary, author, published]
}.each {
println ""
println "article -> ${it[1]}"
println it[0]
println "author -> ${it[3]}"
}
}
output
抓msdn订阅的产品分类信息
new JsonSlurper().parse(new URL("http://msdn.microsoft.com/en-us/subscriptions/json/GetProductCategories?brand=MSDN&localeCode=en-us")).with { rs ->
println rs.collect{ it.Name }
}
output
再说一下代码编辑器。本方案因为使用Groovy这门动态语言,故能够选择一种轻量级的文本编辑器,这里要推荐Sublime。其中文翻译是“高大尚”的意思。从这个小小的文本编辑器所表现出来的丰富功能和极佳的用户体验来看,也确实对得起这个名字了。
优势:
缺点:
最后,分享一段抓取搜房网二手房信息的快速脚本
http://noria.codeplex.com/SourceControl/latest#miles/soufun/soufun.groovy
抓取整理后效果图
行文至此,但愿对爬虫感兴趣的朋友们有所帮助。
网络转载于:http://www.cnblogs.com/stainboy/p/make-crawler-with-groovy-and-jsoup.html