string()函数在XPath中用于将选定节点的值转换为字符串。它的作用是简化对节点内容的提取,尤其是在处理复杂的XML或HTML文档时。
通俗解释:
string()可以把节点的内容变成易于处理的文本格式,方便提取或比较。
作用:
优势:
- 可以直接获取节点的文本,而无需担心子节点的影响。
- 增强可读性和易用性。
举例说明:
假设有以下HTML结构:
from lxml import html
# 复杂的HTML
complex_html = '''
<div>
<h1>Title</h1>
<p>This is <strong>important</strong> text.</p>
<p>Another paragraph.</p>
</div>
'''
# 解析HTML
tree = html.fromstring(complex_html)
# 使用XPath提取文本
result1 = tree.xpath('string(.)')
print(result1)
print('*'*100)
result2 = tree.xpath('string(./h1)')
print(result2)
print('*'*100)
result3 = tree.xpath('string(./p)')
print(result3)
print('*'*100)
输出结果:
Title
This is important text.
Another paragraph.
****************************************************************************************************
Title
****************************************************************************************************
This is important text.
****************************************************************************************************
相关博客:
https://www.cnblogs.com/CYHISTW/p/12312570.html