jsoup使用xpath
时间: 2023-08-26 19:10:52 浏览: 238
使用Jsoup进行XPath查询需要先引入JsoupXpath依赖。在pom.xml文件中添加以下依赖项:
```xml
<dependency>
<!-- jsoup HTML parser library @ https://jsoup.org/ -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.4</version>
</dependency>
<dependency>
<groupId>cn.wanghaomiao</groupId>
<artifactId>JsoupXpath</artifactId>
<version>2.5.3</version>
</dependency>
```
然后,可以使用以下代码示例来执行XPath查询:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import us.codecraft.xsoup.JXDocument;
import us.codecraft.xsoup.JXNode;
public class JsoupXPathExample {
public static void main(String\[\] args) throws IOException {
Document document = Jsoup.connect("https://www.example.com").get();
JXDocument jxDocument = JXDocument.create(document);
List<JXNode> jxNodes = jxDocument.selN("//div\[@class='example'\]");
for (JXNode jxNode : jxNodes) {
Element element = jxNode.asElement();
System.out.println(element.text());
}
}
}
```
在上面的示例中,我们首先使用Jsoup连接到指定的网页,然后创建一个JXDocument对象。接下来,我们使用`selN`方法执行XPath查询,传入XPath表达式作为参数。最后,我们遍历查询结果,并将每个结果转换为Jsoup的Element对象,然后打印出其文本内容。
#### 引用[.reference_title]
- *1* [410、Jsoup的快速查询---使用xpath选择器](https://blog.csdn.net/l0510402015/article/details/104649360)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [JAVA爬虫JsoupXPath](https://blog.csdn.net/huahuaxingjing/article/details/130324268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文