lxml etree xpath

简介: from lxml import etree #####################基本用法: ##################### html = ''' 登录 用户: 密码: ''' # 生成DOM dom = etree.

 

from lxml import etree

#####################
基本用法:
 
 
#####################
html = '''
<h1 class="header">登录</h1>
<form action="/login" method="post">
    <label for="username">用户: </label><input type="text" name="username" />
    <label for="password">密码:</label><input type="password" name="password" />
    <input type="submit" value="Submit" />
</form>'''

# 生成DOM
dom = etree.HTML(html)

# 取内容 /text()
contents = dom.xpath('//h1[@class="header"]/text()')
print(contents)

# 取属性 /@attrib
attribs = dom.xpath('//form/label[@for="username"]/@for')
print(attribs)




##
###################
复杂用法:
#####################
html2 = ''' 
<div class="content">
==> 有相同字符开头的属性的标签:
<p id="test-1">需要的内容1</p>
<p id="test-2">需要的内容2</p>
<p id="test-default">需要的内容3</p>
</div>
<div class="question">
==> 签嵌套标签:
<p id="class3">美女,
      <font color="red">你的微信号是多少?</font>
</p>
</div>
'''

dom = etree.HTML(html2)

# 取有相同字符开头的属性的标签的内容 starts-with(@attrib, "abcd")
contents2 = dom.xpath('//p[starts-with(@id, "test")]/text()')
print(contents2)

# 取标签嵌套标签的所有内容 xpath('string(.)')
contents3 = dom.xpath('//div[@class="question"]/p')[0].xpath('string(.)')
contents3
= contents3.replace('\n', '').replace(' ', '')
print(contents3)

 

目录
相关文章
|
2月前
|
XML 前端开发 数据格式
请描述如何使用`BeautifulSoup`或其他类似的库来解析 HTML 或 XML 数据。
【2月更文挑战第22天】【2月更文挑战第67篇】请描述如何使用`BeautifulSoup`或其他类似的库来解析 HTML 或 XML 数据。
|
4月前
|
容器
readability-lxml 源码解析(四):总结
readability-lxml 源码解析(四):总结
16 0
|
4月前
readability-lxml 源码解析(一)
readability-lxml 源码解析(一)
12 0
|
21天前
|
数据采集 开发者 Python
使用urllib和BeautifulSoup解析网页中的视频链接
使用urllib和BeautifulSoup解析网页中的视频链接
Beauiful Soup
Beautiful Soup的简单使用
|
数据处理 网络安全 Python
Requests+Etree+BeautifulSoup+Pandas+Path+Pyinstaller应用 | 获取页面指定区域数据存入html、excel文档
Requests+Etree+BeautifulSoup+Pandas+Path+Pyinstaller应用 | 获取页面指定区域数据存入html、excel文档
195 0
Requests+Etree+BeautifulSoup+Pandas+Path+Pyinstaller应用 | 获取页面指定区域数据存入html、excel文档
|
XML 数据采集 JavaScript
HTML解析之BeautifulSoup
HTML解析之BeautifulSoup
133 0
|
Python
Beautiful Soup库的介绍
本节中将介绍如何使用 Beautiful Soup 来解析 HTML 以获取我们想要的信息。
78 0
使用lxml.html.clean.Cleaner清洗html
使用lxml.html.clean.Cleaner清洗html
148 0
|
XML 数据采集 SQL
第64天:XPath 和 lxml
第64天:XPath 和 lxml
121 0