首页 新闻 会员 周边

通过Heritrix或者webmagic如何爬去指定url里的内容?

0
悬赏园豆:20 [已解决问题] 解决于 2016-03-29 17:19

现在我有host和url,如何爬取这个url对应的内容呢?求大神指教,用heritrix或者webmagic

wangxing.xu的主页 wangxing.xu | 初学一级 | 园豆:127
提问于:2016-03-29 11:54
< >
分享
最佳答案
1

如果你只想获取这个url对应的内容,用jsoup就可以实现。代码如下:

package com.scistor.datavision.operator.webcrawler.webmagic;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class ReadExample {
public static void main(String[] args) throws IOException {

Document dom = Jsoup
.connect(
"http://www.ibm.com/developerworks/cn/java/j-lo-jsouphtml/")
.get();
String html = dom.outerHtml();
System.out.println(html);
}
}

这里Document是jsoup解析html的容器,有非常丰富的解析方法。

webmagic是一个爬取框架,主要是基于种子url,对它的二级链接进行深度爬取。提供一个非常方便api让你可以轻松的深度爬取,并自己编写解析业务。

收获园豆:20
我还是太年轻 | 小虾三级 |园豆:692 | 2016-03-29 16:57

我现在是有主机名和uri,照你的做法只是解析html文件,我想用爬虫技术去爬取内容,不一定是html文件,也可能是json字符串等等,这该怎么操作呢?

wangxing.xu | 园豆:127 (初学一级) | 2016-03-29 17:06

@wangxing.xu: 没听懂,爬虫技术通常是要深度爬取的,就是对二级链接继续爬取。只对url去解析,通常就是用jsoup,webmagic底层也是用jsoup去解析html的,不过是封装了深度爬取的步骤。

    另外Document这个对象本身就是抽象的,他不仅仅可以容纳html,也能容纳json字符串等等。总之他能容纳url对应的响应内容。

    如果你非要用爬虫技术,我给你贴一下webmagic的示例:

package com.scistor.datavision.operator.webcrawler.webmagic;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

public class GithubRepoPageProcessor implements PageProcessor {

// 部分一:抓取网站的相关配置,包括编码、抓取间隔、重试次数等
private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

// process是定制爬虫逻辑的核心接口,在这里编写抽取逻辑
public void process(Page page) {
// 部分二:定义如何抽取页面信息,并保存下来
page.putField("author",
page.getUrl().regex("https://github\\.com/(\\w+)/.*")
.toString());
page.putField(
"name",
page.getHtml()
.xpath("//h1[@class='entry-title public']/strong/a/text()")
.toString());
if (page.getResultItems().get("name") == null) {
// skip this page
page.setSkip(true);
}
page.putField("readme",
page.getHtml().xpath("//div[@id='readme']/tidyText()"));
Html html = page.getHtml();

// 部分三:从页面发现后续的url地址来抓取
page.addTargetRequests(page.getHtml().links()
.regex("(https://github\\.com/\\w+/\\w+)").all());

}

public Site getSite() {
return site;
}

public static void main(String[] args) {

Spider.create(new GithubRepoPageProcessor())
// 从"https://github.com/code4craft"开始抓
.addUrl("https://github.com/code4craft").addPipeline(new ConsolePipeline())
// 开启5个线程抓取
.thread(5)
// 启动爬虫
.run();
}

我还是太年轻 | 园豆:692 (小虾三级) | 2016-03-29 17:13

@我还是太年轻: 哦,我知道了,我现在是用heritrix爬取指定url的内容,不过你说的jsoup解析html文件挺不错的,document应该提供了解析url的方法,我晚上回去试试,谢谢你的回答

wangxing.xu | 园豆:127 (初学一级) | 2016-03-29 17:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册