XPath
lxml装载HTML代码有如下两种方式:
(1)从文件装载,通过parse函数指定HTML文件名。
(2)从代码装载,通过HTML函数指定HTML代码。
XPath语言的基本语法就是多级目录。
XPath的基本语法规则
nodename 选取此节点的所有子节点
/ 从当前节点选取直接子节点
// 从当前节点选取子孙节点
. 选取当前节点
… 选取当前节点的父节点
@ 选取属性
在lxml中使用XPath需要通过xpath函数指定XPath代码
lxmI中使用XPath过滤节点:
from lxml import etree
parser := etree.HTMLParser ()
tree = etree.parse ( ’ test .html’, parser)
titles = tree . xpath ( ’ /html/head/title ’ )
if len (titles) > 0:
print (titles[0].text)
#定义一段HTML代码
html = ‘’’
- <'a href="https: //geekori.com"> geekori . com
- 京东商城
- 淘宝
分析HTML代码
tree = etree.HTML (html)
aTags = tree . xpath ( "//li [@class='item2 ’ ] ")