Java-WebMagic

原文链接:

webmagic 基本的方法 - 走看看

WebMagic的结构分为DownloaderPageProcessorSchedulerPipeline四大组件,并由Spider将它们彼此组织起来。这四大组件对应爬虫生命周期中的下载、处理、管理和持久化等功能

PageProcessor 需要自己写

Scheduler 除非项目有一些特殊的分布式需求,否则无需自己定制

Pipeline 要保存到数据库需要自己定制

Selectable

方法说明示例
xpath(String xpath)使用XPath选择html.xpath("//div[@class='title']")
$(String selector)使用Css选择器选择html.$("div.title")
$(String selector,String attr)使用Css选择器选择html.$("div.title","text")
css(String selector)功能同$(),使用Css选择器选择html.css("div.title")
links()选择所有链接html.links()
regex(String regex)使用正则表达式抽取html.regex("<div>(.*?)")
regex(String regex,int group)使用正则表达式抽取,并指定捕获组html.regex("<div>(.*?)",1)
replace(String regex, String replacement)替换内容html.replace("","")

 返回结果

方法说明示例
get()返回一条String类型的结果String link= html.links().get()
toString()功能同get(),返回一条String类型的结果String link= html.links().toString()
all()返回所有抽取结果List links= html.links().all()
match()是否有匹配结果if (html.links().match()){ xxx; }

Spider

方法说明示例
create(PageProcessor)创建SpiderSpider.create(new GithubRepoProcessor())
addUrl(String…)添加初始的URLspider .addUrl("Choose a language · WebMagic Documents")
addRequest(Request...)添加初始的Requestspider .addRequest("Choose a language · WebMagic Documents")
thread(n)开启n个线程spider.thread(5)
run()启动,会阻塞当前线程执行spider.run()
start()/runAsync()异步启动,当前线程继续执行spider.start()
stop()停止爬虫spider.stop()
test(String)抓取一个页面进行测试spider .test("Choose a language · WebMagic Documents")
addPipeline(Pipeline)添加一个Pipeline,一个Spider可以有多个Pipelinespider .addPipeline(new ConsolePipeline())
setScheduler(Scheduler)设置Scheduler,一个Spider只能有个一个Schedulerspider.setScheduler(new RedisScheduler())
setDownloader(Downloader)设置Downloader,一个Spider只能有个一个Downloaderspider .setDownloader(new SeleniumDownloader())
get(String)同步调用,并直接取得结果ResultItems result = spider .get("Choose a language · WebMagic Documents")
getAll(String…)同步调用,并直接取得一堆结果List<ResultItems> results = spider .getAll("Choose a language · WebMagic Documents", "http://webmagic.io/xxx")

Site

方法说明示例
setCharset(String)设置编码site.setCharset("utf-8")
setUserAgent(String)设置UserAgentsite.setUserAgent("Spider")
setTimeOut(int)设置超时时间,单位是毫秒site.setTimeOut(3000)
setRetryTimes(int)设置重试次数site.setRetryTimes(3)
setCycleRetryTimes(int)设置循环重试次数site.setCycleRetryTimes(3)
addCookie(String,String)添加一条cookiesite.addCookie("dotcomt_user","code4craft")
setDomain(String)设置域名,需设置域名后,addCookie才可生效site.setDomain("github.com")
addHeader(String,String)添加一条addHeadersite.addHeader("Referer","https://github.com")
setHttpProxy(HttpHost)设置Http代理site.setHttpProxy(new HttpHost("127.0.0.1",8080))

Xsoup

NameExpressionSupport
nodenamenodenameyes
immediate parent/yes
parent//yes
attribute[@key=value]yes
nth childtag[n]yes
attribute/@keyyes
wildcard in tagname/*yes
wildcard in attribute/[@*]yes
functionfunction()part
ora | byes since 0.2.0
parent in path. or ..no
predicatesprice>35no
predicates logic@class=a or @class=byes since 0.2.0

 另外作者自己定义了几个对于爬虫来说,很方便的XPath函数。但是请注意,这些函数式标准XPath没有的。

ExpressionDescriptionXPath1.0
text(n)第n个直接文本子节点,为0表示所有text() only
allText()所有的直接和间接文本子节点not support
tidyText()所有的直接和间接文本子节点,并将一些标签替换为换行,使纯文本显示更整洁not support
html()内部html,不包括标签的html本身not support
outerHtml()内部html,包括标签的html本身not support
regex(@attr,expr,group)这里@attr和group均可选,默认是group0not support

代理

API说明
HttpClientDownloader.setProxyProvider(ProxyProvider proxyProvider)设置代理

1.设置单一的普通HTTP代理为101.101.101.101的8888端口,并设置密码为"username","password"

HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
httpClientDownloader.setProxyProvider(SimpleProxyProvider.from(new Proxy("101.101.101.101",8888,"username","password")));
spider.setDownloader(httpClientDownloader);

2.设置代理池,其中包括101.101.101.101和102.102.102.102两个IP,没有密码

 HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
    httpClientDownloader.setProxyProvider(SimpleProxyProvider.from(
    new Proxy("101.101.101.101",8888)
    ,new Proxy("102.102.102.102",8888)));

HttpRequestBody

API说明
HttpRequestBody.form(Map<string,object> params, String encoding)使用表单提交的方式
HttpRequestBody.json(String json, String encoding)使用JSON的方式,json是序列化后的结果
HttpRequestBody.xml(String xml, String encoding)设置xml的方式,xml是序列化后的结果
HttpRequestBody.custom(byte[] body, String contentType, String encoding)设置自定义的requestBody
 

组件的使用

方法说明示例
setScheduler()设置Schedulerspipder.setScheduler(new FileCacheQueueScheduler("D:datawebmagic"))
setDownloader()设置Downloaderspipder.setDownloader(new SeleniumDownloader()))
addPipeline()设置Pipeline,一个Spider可以有多个Pipelinespipder.addPipeline(new FilePipeline())

结果输出方式

说明备注
ConsolePipeline输出结果到控制台抽取结果需要实现toString方法
FilePipeline保存结果到文件抽取结果需要实现toString方法
JsonFilePipelineJSON格式保存结果到文件
ConsolePageModelPipeline(注解模式)输出结果到控制台
FilePageModelPipeline(注解模式)保存结果到文件
JsonFilePageModelPipeline(注解模式)JSON格式保存结果到文件想要持久化的字段需要有getter方法
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值