org.jsoup.select.Selector

本文详细解析了JSoup库中的元素选择器,包括CSS-like元素选择器、组合符、伪类选择器、伪元素选择器等,帮助开发者理解和应用这些选择器进行网页内容的提取和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

org. jsoup. select.Selector

 

CSS-like element selector, that finds elements matching a query.

Selector syntax

A selector is a chain of simple selectors, separated by combinators. Selectors are case insensitive (including against elements, attributes, and attribute values).

The universal selector (*) is implicit when no element selector is supplied (i.e. *.header and .header is equivalent).

PatternMatchesExample
*any element*
tagelements with the given tag namediv
ns|Eelements of type E in the namespace nsfb|name finds <fb:name>elements
#idelements with attribute ID of "id"div#wrap#logo
.classelements with a class name of "class"div.left.result
[attr]elements with an attribute named "attr" (with any value)a[href][title]
[^attrPrefix]elements with an attribute name starting with "attrPrefix". Use to find elements with HTML5 datasets[^data-]div[^data-]
[attr=val]elements with an attribute named "attr", and value equal to "val"img[width=500],a[rel=nofollow]
[attr="val"]elements with an attribute named "attr", and value equal to "val"span[hello="Cleveland"][goodbye="Columbus"],a[rel="nofollow"]
[attr^=valPrefix]elements with an attribute named "attr", and value starting with "valPrefix"a[href^=http:]
[attr$=valSuffix]elements with an attribute named "attr", and value ending with "valSuffix"img[src$=.png]
[attr*=valContaining]elements with an attribute named "attr", and value containing "valContaining"a[href*=/search/]
[attr~=regex]elements with an attribute named "attr", and value matching the regular expressionimg[src~=(?i)\\.(png|jpe?g)]
 The above may be combined in any orderdiv.header[title]
 

Combinators

E Fan F element descended from an E elementdiv a.logo h1
E > Fan F direct child of Eol > li
E + Fan F element immediately preceded by sibling Eli + lidiv.head + div
E ~ Fan F element preceded by sibling Eh1 ~ p
E, F, Gall matching elements E, F, or Ga[href], div, h3
 

Pseudo selectors

:lt(n)elements whose sibling index is less than ntd:lt(3) finds the first 3 cells of each row
:gt(n)elements whose sibling index is greater thanntd:gt(1) finds cells after skipping the first two
:eq(n)elements whose sibling index is equal to ntd:eq(0) finds the first cell of each row
:has(selector)elements that contains at least one element matching the selectordiv:has(p) finds divs that contain p elements
:not(selector)elements that do not match the selector. See also Elements.not(String)div:not(.logo) finds all divs that do not have the "logo" class.

div:not(:has(div)) finds divs that do not contain divs.

:contains(text)elements that contains the specified text. The search is case insensitive. The text may appear in the found element, or any of its descendants.p:contains(jsoup) finds p elements containing the text "jsoup".
:matches(regex)elements whose text matches the specified regular expression. The text may appear in the found element, or any of its descendants.td:matches(\\d+) finds table cells containing digits.div:matches((?i)login) finds divs containing the text, case insensitively.
:containsOwn(text)elements that directly contain the specified text. The search is case insensitive. The text must appear in the found element, not any of its descendants.p:containsOwn(jsoup) finds p elements with own text "jsoup".
:matchesOwn(regex)elements whose own text matches the specified regular expression. The text must appear in the found element, not any of its descendants.td:matchesOwn(\\d+) finds table cells directly containing digits. div:matchesOwn((?i)login) finds divs containing the text, case insensitively.
 The above may be combined in any order and with other selectors.light:contains(name):eq(0)

Structural pseudo selectors

:rootThe element that is the root of the document. In HTML, this is the html element:root
:nth-child(an+b)

elements that have an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a andb values must be integers (positive, negative, or zero). The index of the first child of an element is 1.

In addition to this, :nth-child() can takeodd and even as arguments instead. odd has the same signification as 2n+1, and even has the same signification as 2n.
tr:nth-child(2n+1) finds every odd row of a table. :nth-child(10n-1) the 9th, 19th, 29th, etc, element. li:nth-child(5) the 5h li
:nth-last-child(an+b)elements that have an+b-1 siblings after it in the document tree. Otherwise like :nth-child()tr:nth-last-child(-n+2) the last two rows of a table
:nth-of-type(an+b)pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent elementimg:nth-of-type(2n+1)
:nth-last-of-type(an+b)pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name after it in the document tree, for any zero or positive integer value of n, and has a parent elementimg:nth-last-of-type(2n+1)
:first-childelements that are the first child of some other element.div > p:first-child
:last-childelements that are the last child of some other element.ol > li:last-child
:first-of-typeelements that are the first sibling of its type in the list of children of its parent elementdl dt:first-of-type
:last-of-typeelements that are the last sibling of its type in the list of children of its parent elementtr > td:last-of-type
:only-childelements that have a parent element and whose parent element hasve no other element children 
:only-of-typean element that has a parent element and whose parent element has no other element children with the same expanded element name 
:emptyelements that have no children at all 
Author:
Jonathan Hedley, jonathan@hedley.net
See Also:
Element.select(String)
<think>我们正在处理一个关于Jsoup解析HTML时出现的空指针异常问题。异常信息是"Cannot invokeElement.html()because 'goodsList' isnull"。这意味着我们尝试在一个为null的Element对象上调用html()方法。 根据引用[2]和引用[3]中的信息,这类异常通常是因为某个对象没有被正确初始化(即它为null)而导致的。在Jsoup的上下文中,这通常意味着我们试图通过选择器获取一个元素,但该元素在文档中不存在,因此返回了null。解决步骤:1.**确认选择器是否正确**:首先检查用于获取`goodsList`元素的选择器字符串是否正确。如果选择器写错了,Jsoup可能找不到元素,从而返回null。 2. **检查HTML文档结构**:确保目标HTML文档中确实存在符合选择器条件的元素。可以通过打印整个文档的HTML来检查,或者使用开发工具查看网页结构。 3. **处理可能为null的情况**:在代码中,我们应该对`goodsList`进行空值检查,避免在null上调用方法。 4. **异常处理**:使用try-catch捕获异常,并给出有意义的错误信息。5.**日志记录**:在关键步骤添加日志,以便于调试。示例代码: 假设我们有以下代码导致异常:```javaDocumentdoc =Jsoup.parse(htmlString);Element goodsList =doc.selectFirst(".goods-list");//如果这个选择器没有匹配到任何元素,goodsList就是nullStringhtml =goodsList.html();//当goodsList为null时,这里就会抛出NullPointerException```修改后的代码:```javaDocumentdoc =Jsoup.parse(htmlString);Element goodsList =doc.selectFirst(".goods-list"); if(goodsList !=null){String html= goodsList.html();//处理html内容}else {//处理元素不存在的情况,例如打印错误信息或记录日志System.err.println("Element withselector'.goods-list'not found."); }``` 或者使用try-catch:```javatry{Document doc= Jsoup.parse(htmlString);Element goodsList =doc.selectFirst(".goods-list");String html= goodsList.html(); //如果goodsList为null,这里会抛出NullPointerException//处理html内容}catch (NullPointerException e) {System.err.println("Failedto getelement:goodsList isnull.Selector mightbe incorrectorelementnot present.");} ```但是,更推荐使用空值检查,因为这样更清晰,而且避免使用异常来处理正常的控制流。另外,根据引用[3],如果是外部项目,还需要检查环境配置,比如依赖的库是否正确导入,以及HTML内容是否如预期被加载(可能因为网络问题或权限问题导致HTML内容为空)。 总结:-检查选择器是否正确-确保HTML文档包含目标元素-在代码中添加空值检查-确保Jsoup正确解析了HTML(检查htmlString是否有效) 相关问题:1.如何调试Jsoup选择器?2.Jsoup中还有哪些常见的选择器用法?3.如何处理Jsoup解析时可能出现的其他异常?</think>### 解决 Jsoup 中 "Cannot invoke Element.html() because 'goodsList' is null" 异常 当使用 Jsoup 解析 HTML 时出现 `Cannot invoke Element.html() because 'goodsList' is null` 错误,说明您尝试在 `null` 对象上调用 `.html()` 方法。以下是系统化的解决步骤: #### 1. **检查元素选择器是否正确** ```java // 错误示例:选择器可能不匹配文档结构 Element goodsList = doc.selectFirst(".goods-list"); // 正确做法:添加空值检查 if (goodsList != null) { String htmlContent = goodsList.html(); } else { System.out.println("元素未找到!请检查选择器"); } ``` - 使用开发者工具(浏览器按 F12)验证目标元素的选择器 - 尝试更通用的选择器如 `doc.select("div")` 逐步定位问题元素 #### 2. **验证 HTML 文档是否成功加载** ```java // 检查文档是否有效 Document doc = Jsoup.connect(url).get(); System.out.println("文档标题: " + doc.title()); // 验证文档加载 // 或检查原始 HTML String rawHtml = doc.html(); System.out.println(rawHtml.contains("goods-list")); // 确认目标元素存在 ``` #### 3. **处理网络/加载异常** ```java try { Document doc = Jsoup.connect("https://example.com") .timeout(10000) // 设置超时 .get(); } catch (IOException e) { e.printStackTrace(); // 捕获网络异常 } ``` #### 4. **完整解决方案示例** ```java public String getGoodsListHtml(String url) { try { Document doc = Jsoup.connect(url).timeout(8000).get(); // 使用更健壮的选择器 Element goodsList = doc.selectFirst("#product-section > .goods-list"); if (goodsList == null) { // 尝试备用选择器 goodsList = doc.selectFirst(".product-container"); } return (goodsList != null) ? goodsList.html() : "元素不存在"; } catch (IOException e) { return "页面加载失败: " + e.getMessage(); } } ``` #### 常见原因总结: | 原因 | 解决方案 | |------|----------| | 选择器错误 | 使用开发者工具验证 CSS 选择器 | | 页面未加载 | 检查网络连接和超时设置 | | 动态内容未渲染 | 使用 Selenium 等工具获取渲染后 HTML | | 元素不存在 | 添加 null 检查逻辑 | > **关键点**:在调用任何 Jsoup 元素方法前,必须进行空值检查。根据引用[3],对象未初始化导致的 `NullPointerException` 是 Java 项目迁移时的常见问题,需重点检查元素获取逻辑[^3]。 --- ### 相关问题 1. 如何验证 Jsoup 选择器在动态网页中的有效性? 2. Jsoup 和 Selenium 在解析动态内容时有哪些主要区别? 3. 除了空指针异常,Jsoup 解析 HTML 时还有哪些常见错误需要处理?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值