文章目录
一、Xpath语法
xpath是一门在XML文档中查找信息的语言
1、 节点(Node)
元素、属性、文本、命名空间、文档(根)节点
2、 节点关系
父(parent)
子 (Children)
同胞 (Sibling)
先辈 (Ancestor)
后代 (Descendant)
3、 xpath语法
| 表达式 | 描述 |
|---|---|
| nodename | 选取此节点的所有子节点 |
| // | 从任意子节点中选取(第一级) |
| / | 从根节点选取(下级) |
| . | 选取当前节点(同级) |
| … | 选取当前节点的父节点(上级) |
| @ | 选取属性 |
4、 获取信息
text():获取文本信息
[last()-1]:倒数第二个,即最后一个 - 1
@class:选取class属性
position()<5:选取前4个
5、 解析器比较
| 解析器 | 速度 | 难度 |
|---|---|---|
| re | 最快 | 难 |
| BeautifulSoup | 慢 | 非常简单 |
| lxml | 快 | 简单 |
6、Xpath练习
from lxml import etree
import requests
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://exa

最低0.47元/天 解锁文章
456

被折叠的 条评论
为什么被折叠?



