使用JSOUP实现网络爬虫:使用DOM方法来遍历一个文档
问题
你有一个HTML文档要从中提取数据,并了解这个HTML文档的结构。
方法
将HTML解析成一个Document之后,就可以使用类似于DOM的方法进行操作。示例代码:
view plain copy print?
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
说明
Elements这个对象提供了一系列类似于DOM的方法来查找元素,抽取并处理其中的数据。具体如下:
查找元素
getElementById(String id)
getElementsByTag(String tag)
getElementsByClass(String className)
getElementsByAttribute(String key)
(and related methods)- Element siblings:
siblingElements()
,firstElementSibling()
,lastElementSibling()
;nextElementSibling()
,previousElementSibling()
- Graph:
parent()
,children()
,child(int index)
attr(String key)
获取属性attr(String key, String value)
设置属性attributes()
获取所有属性id()
,className()
andclassNames()
text()
获取文本内容text(String value)
设置文本内容html()
获取元素内HTMLhtml(String value)
设置元素内的HTML内容outerHtml()
获取元素外HTML内容data()
获取数据内容(例如:script和style标签)tag()
andtagName()
append(String html)
,prepend(String html)
appendText(String text)
,prependText(String text)
appendElement(String tagName)
,prependElement(String tagName)
html(String value)
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 铭记光荣历史展望美好未来 7904331
- 2 央视曝白家电诈园区虐待手段:极残酷 7808210
- 3 张家界司机用生命救下一车韩国游客 7712582
- 4 怎样看懂防汛高频词 7617672
- 5 “大圣同款”泳衣卖爆了 7520539
- 6 电诈回流人员:被强迫卖淫 要做满1年 7428232
- 7 院士预测广东8级地震?官方通报 7332880
- 8 《大展鸿图》原唱回应“赚了1.2亿” 7233219
- 9 陈龙突击检查父母开空调 7143658
- 10 一斤超百元 知了猴怎么就火出圈了 7042792