Html解析库Jsoup使用记录

一、添加gradle依赖

implementation ‘org.jsoup:jsoup:1.16.1’

二、使用Jsoup

解析html文本字符串为Document

val doc: Document = Jsoup.parse(webSrc)

select方法的使用

 public Elements select(String cssQuery) {
        return Selector.select(cssQuery, this);
 }

Jsoup 的 select 方法使用 CSS 选择器 来查找和筛选 HTML 元素

  1. 根据标签名选择元素
Elements paragraphs = doc.select("p");  // 选择所有 <p> 标签
  1. 根据类名选择元素
    使用 . 来选择特定类名的元素。
Elements items = doc.select(".item");  // 选择所有 class="item" 的元素
  1. 根据 ID 选择元素
    使用 # 来选择特定 ID 的元素。
Element header = doc.select("#header").first();  // 选择 id="header" 的元素
  1. 根据属性选择元素
Elements links = doc.select("a[href]");  // 选择所有带有 href 属性的 <a> 标签
Elements images = doc.select("img[src]");  // 选择所有带有 src 属性的 <img> 标签
  1. 根据属性和值选择元素
Elements specificLinks = doc.select("a[href='http://example.com']");  // 选择 href 属性等于 "http://example.com" 的 <a> 标签
  1. 选择嵌套的元素
    可以使用父子选择器查找嵌套关系中的元素。
Elements divParagraphs = doc.select("div > p");  // 选择所有直接位于 <div> 内的 <p> 标签
  1. 使用索引选择元素
    可以通过 :nth-child() 或 :eq() 选择特定位置的元素。
Element secondDiv = doc.select("div:nth-child(2)").first();  // 选择第二个 <div> 元素
  1. 伪类选择器
    使用伪类选择器选择特定类型的元素。
Elements lastItems = doc.select("li:last-child");  // 选择列表中的最后一个 <li> 元素
  1. 组合选择器
    可以组合多种选择器来筛选更加复杂的元素。
Elements combined = doc.select("div#content .item[title]");  // 选择 id 为 content 的 <div> 内的 class 为 item 且带有 title 属性的元素
  1. 查找包含特定文本的元素
    使用 :contains(text) 来选择包含特定文本的元素。
Elements containsText = doc.select("p:contains(Hello)");  // 选择包含 "Hello" 文本的 <p> 标签
  1. 查找空元素
Elements emptyDivs = doc.select("div:empty");  // 选择所有没有子元素的 <div>
  1. 查找兄弟元素
    使用 ~ 查找同级兄弟元素。
Elements siblingDivs = doc.select("div ~ div");  // 选择和某个 <div> 同级的后续所有 <div> 元素
  1. 选择多个不同类型的元素
Elements elements = doc.select("a, div");  // 选择所有 <a> 和 <div> 标签