解析Html源码
在上一篇中,获取了网页的html源码,但是里面东西太多了,并不是我们想要的结果
所以我们需要提取我们想要的结果
使用Selectable接口,你可以直接完成页面元素的链式抽取,也无需去关心抽取的细节。
我们通过Page对象获取了html对象,如果深入的话会发现,Html对象的父类实现了Selectable接口,它是可以进行提取元素的。
Selectable中的部分API
方法
说明
示例xpath(String xpath)
使用XPath选择
html.xpath("//div[@class=‘title’]")
$(String selector)
使用Css选择器选择
html.$(“div.title”)
$(String selector,String attr)
同上,获取的是标签内容
html.$(“div.title”,“text”)
css(String selector)
功能同$() 使用Css选择器选择
html.css(“div.title”)
links()
选择所有链接
html.links()
regex(String regex)
使用正则表达式抽取
html.regex("(.*?)")
regex(String regex,int group)
使用正则表达式抽取,并指定捕获组
html.regex("(.*?)",1)
replace(String regex, String replacement)
替换内容
html.replace("","")
CSS选择器
选择器
例子
例子描述.class
.intro
选择 class=“intro” 的所有元素。
#id
#firstname
选择 id=“firstname” 的所有元素。
element
p
选择所有 < p > 元素。
element,element
div,p
选择所有 < di