使用webmagic获取github的仓库名
时间: 2023-11-28 20:38:45 浏览: 28
以下是使用webmagic获取github仓库名的示例代码:
``` java
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
public class GithubRepoPageProcessor implements PageProcessor {
private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);
@Override
public void process(Page page) {
// 从页面中提取所有仓库名
List<String> repoList = page.getHtml().xpath("//h3/a/text()").all();
// 输出仓库名
System.out.println("Github repositories:");
for (String repo : repoList) {
System.out.println(repo);
}
}
@Override
public Site getSite() {
return site;
}
public static void main(String[] args) {
Spider.create(new GithubRepoPageProcessor())
.addUrl("https://github.com/explore")
.addPipeline(new ConsolePipeline())
.run();
}
}
```
在该示例代码中,我们使用了webmagic框架的PageProcessor接口来处理页面并提取所需的数据。
在process方法中,我们使用了XPath语法来提取页面中所有仓库名,并将它们输出到控制台中。
在main方法中,我们创建了一个Spider对象,并指定了要爬取的起始URL。我们还添加了一个控制台输出的Pipeline,以便我们可以看到提取的数据。最后,我们调用run方法来启动爬虫。
需要注意的是,在爬取github网站时,我们需要设置User-Agent头来模拟浏览器访问。我们可以在Site对象中设置User-Agent头,如上述代码中的例子所示。