xpath解析html
时间: 2023-11-08 18:49:32 浏览: 122
XPath是一种用于在XML和HTML文档中进行导航和查找的语言。下面是一些使用XPath解析HTML的示例:
1. 使用Python的lxml库:
```python
from lxml import html
import requests
# 发送请求获取网页内容
page = requests.get('https://www.example.com/')
# 将HTML文本转换为Element对象
tree = html.fromstring(page.content)
# 使用XPath选择器获取元素
title = tree.xpath('//title/text()')[0]
print(title)
```
2. 使用Javascript的Cheerio库:
```javascript
const cheerio = require('cheerio')
const request = require('request')
// 发送请求获取网页内容
request('https://www.example.com/', (error, response, html) => {
// 将HTML文本转换为Cheerio对象
const $ = cheerio.load(html)
// 使用XPath选择器获取元素
const title = $('title').text()
console.log(title)
})
```
无论使用哪种库,都可以使用XPath语法来选择HTML元素。要了解更多XPath语法,请参考XPath教程。
阅读全文
相关推荐














