- pip install lxml
- 什么是xpath?
- xml是用来存储和传输数据使用的
和html的不同有两点:
- (1)html用来显示数据,xml是用来传输数据
- (2)html标签是固定的,xml标签是自定义的
- xpath用来在xml中查找指定的元素,它是一种路径表达式
常用的路径表达式
// : 不考虑位置的查找
./ : 从当前节点开始往下查找
@ : 选取属性实例:
- /bookstore/book
- 选取根节点bookstore下面所有直接子节点book
- //book
- 选取所有book
- bookstore//book
- 查找bookstore下面所有的book
- /bookstore/book[1]
- bookstore里面的第一个book
- /bookstore/book[last()]
- bookstore里面的最后一个book
- /bookstore/book[position()<3]
- 前两个book
- //title[@lang]
- 所有的带有lang属性的title节点
- //title[@lang=’eng’]
- 所有的lang属性值为eng的title节点
- /bookstore/book
任何元素节点
- 安装xpath插件
- 将xpath插件拖动到谷歌浏览器扩展程序中,安装成功
- 启动和关闭插件
- ctrl + shift + x
- 属性定位
- //input[@id=”kw”]
- //input[@class=”bg s_btn”]
- 层级定位
- 索引定位
- //div[@id=”head”]/div/div[2]/a[@class=”toindex”]
- 【注】索引从1开始
- //div[@id=”head”]//a[@class=”toindex”]
- 【注】双斜杠代表下面所有的a节点,不管位置
- //div[@id=”head”]/div/div[2]/a[@class=”toindex”]
- 逻辑运算
- //input[@class=”s_ipt” and @name=”wd”]
- 模糊匹配
- contains
- //input[contains(@class, “s_i”)]
- 所有的input,有class属性,并且属性中带有s_i的节点
- //input[contains(text(), “爱”)]
- //input[contains(@class, “s_i”)]
- starts-with
- //input[starts-with(@class, “s”)]
- 所有的input,有class属性,并且属性以s开头
- //input[starts-with(@class, “s”)]
- contains
取文本
- //div[@id=”u1”]/a[5]/text() 获取节点内容
- //div[@id=”u1”]//text()
获取节点里面不带标签的所有内容
直接将所有的内容拼接起来返回给你
- ret = tree.xpath(‘//div[@class=”song”]’)
- string = ret[0].xpath(‘string(.)’)
- print(string.replace(‘\n’, ‘’).replace(‘\t’, ‘’))
- 取属性
- //div[@id=”u1”]/a[5]/@href
- 安装xpath插件
代码中使用xpath
- from lxml import etree
- 两种方式使用:将html文档变成一个对象,然后调用对象的方法去查找指定的节点
- (1)本地文件
- tree = etree.parse(文件名)
(2)网络文件
- tree = etree.HTML(网页字符串)
ret = tree.xpath(路径表达式)
- 【注】ret是一个列表
1 | import urllib.request |