使用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 中央经济工作会议在北京举行 7904806
- 2 紧急提醒:请在日中国公民进行登记 7809154
- 3 中央定调明年继续“国补” 7711954
- 4 “九天”无人机成功首飞 7617964
- 5 断崖式降温!今冬最强寒潮来了 7521782
- 6 中央经济工作会议释信号:3件事不做 7429224
- 7 中国“空中航母”首飞成功 7328329
- 8 00后女生摆摊卖水培蔬菜日售千元 7236987
- 9 人民空军中日双语发文:大惊小怪 7138468
- 10 寒潮来袭 “速冻”模式如何应对 7040497







程序猿
