XML 指可扩展标记语言(EXtensible Markup Language)。XML 是一种标记语言,很类似 HTML。XML 的设计宗旨是传输数据,而非显示数据。被设计为传输和存储数据,其焦点是数据的内容。
XML 是 W3C 的推荐标准 W3School官方文档:http://www.w3school.com.cn/xml/index.asp
XPath (XML Path Language) 是一门在 XML 文档中查找信息的语言,可用来在 XML 文档中对元素和属性进行遍历。

XPath语法

属性[@]与筛选条件要放在中括号里     //title/text()得到title下面的文本信息      地址href与src要用@ /@href  /@src
爬虫------XPath与lxml

路径表达式

/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3]选取最前面的两个属于bookstore元素的子元素的book元素
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang=’eng’]选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00] 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。

安装lxml

Python3中安装需要安装C语言库,可使用 pip3 安装:sudo pip3 install lxml
from lxml import etree
# 读取外部文件 hello.html
html = etree.parse('./hello.html')
#利用etree.HTML,将字符串解析为HTML文档对象能用xpath
html = etree.HTML(html)
#按字符串序列化HTML文档
result  = etree.tostring(html)

XPath实例测试(用xpath语言)返回一个列表

1. 获取所有的 <li> 标签
from lxml import etree
html = etree.parse('./hello.html')
result = html.xpath('//li')
继续获取<li> 标签的所有 class属性
result = html.xpath('//li/@class')
获取内容文本
result = html.xpath('//li/@class/text()')
获取内容文本里的第一个
result = html.xpath('//li/@class/text()[“1”]')
取消xpath获取的文本中的\r\n可以循环打印或者转化为字符串类型
得到所有条目的列表模糊匹配(关键词)xpath://div[contains(@id, 'qiushi_tag_')]

保存到指定文件夹

   if not os.path.exists("./images/"):
         os.makedirs("./images/")
      #这种写法不用去关闭,帮我们关闭
      with open("./images/"+str(image_name)+".png","wb") as f:
         f.write(content)

1. 字符串转列表

str1 = "hi hello world"
print(str1.split(" "))
输出:['hi', 'hello', 'world']

2. 列表转字符串

l = ["hi","hello","world"]
print(" ".join(l))
输出:hi hello world

相关文章: