search
python Xpath syntaxNov 26, 2020 pm 05:11 PM
pythonxpath

python video tutorial column introduces the Xpath syntax of python.

python Xpath syntax

1. Introduction to XML

(1) What is XML

  • XML refers to Extensible Markup Language (EXtensible)
  • XML is a markup language, very similar to HTML.
  • XML is designed to transmit data, not display it.
  • XML tags need to be defined by ourselves.
  • XML is designed to be self-describing.
  • XML is a W3C recommended standard.

W3School official document: http://www.w3school.com.cn/xml/index.asp

(2) The difference between XML and HTML

Both of them are used to manipulate data or structure data. They are roughly the same in structure, but there are obvious differences in their essence.

Data Format Description Design Goal
XML Extensible Markup Language (Extensible Markup Language) is designed to transmit and store data, and its focus is the content of the data.
HTML HyperText Markup Language Display data and how to better display data.
HTML DOM Document Object Model for HTML Through HTML DOM, all HTML elements can be accessed. along with the text and attributes they contain. The content can be modified and deleted, and new elements can also be created.

(3) XML node relationship

<?XML  version=&#39;1.0&#39; encoding=""utf-8><book>
	<title>Harry Potter</title>
	<author>J K.Rowling</author>
	<year>2005</year>
	<price>29.00</price></book>

1. Parent

Each element and attribute has a parent . The above is a simple XML example. The book element is the parent of the title, author, year and price elements

2. Children(Children)

The element node can have zero, one or more child elements. In the above example, the title, author, year and price elements are all child elements of the book element

3. Sibling(Sibling)

Nodes that have the same parent. In the above example, the title, author, year, and price elements are all siblings

4. Ancestor

The parent of a node, the parent of the parent, and so on. In the above example, the ancestors of the title element are the book element and the bookstore element

5. Descendant

The child of a certain node, the child of the child, etc. In the above example, the descendants of bookstore are book, title, author, year and price elements:

2. XPATH

XPath (XML Path Language) is a method for searching in XML documents A message language that can be used to traverse elements and attributes in XML documents.

(1) Select nodes

XPath uses path expressions to select nodes or node sets in XML documents. These path expressions are very similar to those we see in regular computer file systems. The most commonly used path expressions are listed below:

Expression Description
nodename Select all child nodes of this node.
/ Select from node.
// Selects nodes in the document from the current node matching the selection, regardless of their position.
. Select the current node.
.. Select the parent node of the current node.
@ Select attributes.

在下面的表格中,我们已列出了一些路径表达式以及表达式的结果:

路径表达式 描述
bookstore 选取 bookstore 元素的所有子节点
/bookstore 选取根元素 bookstore。代表元素的绝对路径。
bookstore/book 选取属于 bookstore 的子元素的所有 book 元素。
//book 选取所有 book 子元素,而不管它们在文档中的位置
bookstore//book 选择属于 booksore 元素的后代所有的 book 元素,而不管他们位于 bookstore 之下的什么位置。
//@lang 选取名为 lang 的所有属性。
text() 取标签当中的值

(二)谓语(Predicates)

谓语用来查找某个特定的节点或者包含某个指定的值的节点,被嵌在方括号中。在下面的表格中,我们列出了带有谓语的一些路径表达式,以及表达式的结果:

路径表达式 描述
/bookstore/book[l] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position() 选最前面的一个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有属性名为 lang 的属性的 title 元素。
//titlel@lang=‘eng’] 选取所有 tltle 元素,且这些元素有属性值为 eng 的 lang 属性。

(三)选取未知节点

XPath 通配符可用来选取未知的 XML 元素。

通配符 描述
* 匹配任何元素节点。
@* 匹配任何属性节点。

在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:

路径表达式 描述
/bookstore/* 选取 bookstore 元素的所有子元素
//* 选取文档中的所有元素。
//title[@*] 选取所有带有属性的 title 元素。

(四)选取若干路径

通过在路径表达式中使用“|”运算符,您可以选取若干个路径。在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:

路径表达式 描述
//book/title //book/price
//title //price
//price 选取文档中所有的 price 元素。

三、lxml 模块

(一)lxml 简介与安装

lxml 是一个 HTML/XML 的解析器,主要的功能是如何解析和提取 HTML/XML 数据。我们可以利用之前学习的 XPath 语法,来快速的定位特定元素以及节点信息。
安装方法:pip install lxml

(二)lxml 初步使用

1、解析HTML字符串

XML 素材:http://www.cnblogs.com/zhangboblogs/p/10114698.html
小结:lxml 可以自动修正 html 代码,例子里不仅补全了 li 标签,还添加了 body,html 标签。

2.、lxml 文件读取

XML 素材:http://www.cnblogs.com/zhangboblogs/p/10114698.htm
除了直接读取字符串,lxml 还支持从文件里读取内容。我们新建一个 hello.html 文件,再利用 etree.parse()方法来读取文件。
注意:从文件中读取数据,要求文件内容符合 xml 格式,如果标签缺失,则不能正常读取。

四、XPath 节点信息解析:

# 安装lxml: pip install lxml

# 1. 导入etree: 两种导入方式
# 第一种: 直接导入
from lxml import etree
# 注意: 此种导入方式,可能会导致报错(etree下面会出现红色波浪线,不影响正常使用)

# 第二种: 
# from lxml import html
# etree = html.etree

str = '<bookstore>' \
            '<book>' \
                '<title>Harry Potter</title>' \
                '<price>29.99</price>' \
            '</book>' \
            '<book>' \
                '<title>Learning XML</title>' \
                '<price>39.95</price>' \
            '</book>' \
            '<book>' \
                '<title>西游记</title>' \
                '<price>69.95</price>' \
            '</book>' \
            '<book>' \
                '<title>水浒传</title>' \
                '<price>29.95</price>' \
            '</book>' \
            '<book>' \
                '<title>三国演义</title>' \
                '<price>29.95</price>' \
            '</book>' \
        '</bookstore>'


# 2. etree.HTML() 将字符串转换成HTML元素对象,可以自动添加缺失的元素
html = etree.HTML(str)  # <element>  是一个el对象
# print(html)


# 3. 方法:
# 3.1 tostring()  查看转换之后的内容(二进制类型)
# 如果想要查看字符串,需要解码
# 如果想要显示汉字,需要先编码,再解码
# content = etree.tostring(html,encoding='utf-8')
# print(content.decode())


# 3.2 xpath()方法  作用:提取页面数据,返回值是一个列表
# xpath的使用一定是建立在etree.HTML()之后的内容中的

# xpath是如何来提取页面数据的?
# 答:使用的是路径表达式

# 3.2.1 xpath路径分为两种:
# 第一种: /  代表一层层的查找,如果/存在于开头,代表根路径
# bookstore = html.xpath('/html/body/bookstore')
# print(bookstore)  # [<element>]

# 第二种: // 任意路径  焦点在元素身上
# 例如:查找bookstore标签
# bookstore = html.xpath('//bookstore')
# print(bookstore)  # [<element>]

# 第一种和第二种结合
# 例如:查找所有book标签
# book = html.xpath('//bookstore/book')
# print(book)  # [<element>, <element>, <element>, <element>, <element>]

# 3.2.2 /text()  获取标签之间的内容
# 例如:获取所有title标签的内容
# 步骤:
# 1. 找到所有title标签
# 2. 获取内容
# title = html.xpath('//book/title/text()')
# print(title)  # ['Harry Potter', 'Learning XML', '西游记', '水浒传', '三国演义']

# 3.3 位于  使用[]  可以理解成条件
# 3.3.1 [n] 代表获取第n个元素,n是数字,n / = / 3]/title/text()')
# print(title)  # ['水浒传', '三国演义']
# ? title = html.xpath('//book[position()>last()-2]/title/text()')
# print(title)  # ['水浒传', '三国演义']

# 3.3.3 获取属性值:@属性名

# 例如: 获取lang属性值为cng的title标签的内容
# title = html.xpath('//book/title[@lang="cng"]/text()')
# print(title)  # ['西游记']

# 例如: 获取包含src属性得title标签的内容
# title = html.xpath('//book/title[@src]/text()')
# print(title)  # ['Harry Potter', '水浒传', '三国演义']

# 例如: 获取包含属性的title标签的内容
# title = html.xpath('//book/title[@*]/text()')
# print(title)  # ['Harry Potter', 'Learning XML', '西游记', '水浒传', '三国演义']

# 例如: 获取最后一个title标签的src属性的值
# title = html.xpath('//book[last()]/title/@src')
# print(title)  # ['https://www.jd.com']

# 例如: 获取所有包含src属性的标签之间的内容
# node = html.xpath('//*[@src]/text()')
# print(node)  # ['Harry Potter', '水浒传', '三国演义']


# 3.4 and  与  连接的是谓语(条件)
# 例如: 获取lang="dng"并且class="t1"的title标签的内容
# title = html.xpath('//book/title[@lang="dng" and @class="t1"]/text()')
# title1 = html.xpath('//book/title[@lang="dng"][@class="t1"]/text()')
# print(title)  # ['三国演义']
# print(title1)  # ['三国演义']


# 3.5 or  或  连接谓语
# 例如: 查找lang="cng"或者lang="bng"的title标签的内容
# title = html.xpath('//book/title[@lang="cng" or @lang="bng"]/text()')
# print(title)  # ['Harry Potter', '西游记']


# 3.6 |  连接路径
# 例如: 获取所有title标签和price标签之间的内容
# title = html.xpath('//title/text() | //price/text()')
# print(title)  # ['Harry Potter', '29.99', 'Learning XML', '39.95', '西游记', '69.95', '水浒传', '29.95', '三国演义', '29.95']


# 3.8 parse()  作用:从文件中读取数据
# 注意: 读取的文件,必须满足xml格式**(不存在单标签,全部都是上标签)**
content = etree.parse('test.html')
# print(content)  # <lxml.etree._elementtree>
res = etree.tostring(content,encoding='utf-8')
print(res.decode())  
nbsp;html>


    <title>test</title>


    <h1>
        这是一个html
    </h1>

</lxml.etree._elementtree></element></element></element></element></element></element></element></element>

相关免费学习推荐:python视频教程

The above is the detailed content of python Xpath syntax. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)