from lxml import etree# XML文档示例
xml_doc = """
<root><book><title>Python编程指南</title><author>张三</author></book><book><title>Python高级编程</title><author>李四</author></book>
</root>
"""# 创建ElementTree对象并解析XML文档
root = etree.fromstring(xml_doc)# 使用XPath定位元素并打印内容
books = root.xpath('//book')
for book in books:title = book.xpath('title/text()')[0]author = book.xpath('author/text()')[0]print(f"书名:{title},作者:{author}")
# HTML文档示例
html_doc = """
<html>
<body><h1>标题</h1><p>段落1</p><p>段落2</p>
</body>
</html>
"""# 创建HTML解析器并解析HTML文档
parser = etree.HTMLParser()
root = etree.fromstring(html_doc, parser)# 遍历HTML元素并打印内容
for element in root.iter():print(element.tag, element.text)
from lxml import html
import requests# 发送HTTP请求获取网页内容
response = requests.get('https://example.com')
html_content = response.content# 使用lxml解析HTML内容并提取信息
tree = html.fromstring(html_content)
title = tree.xpath('//title/text()')[0]
paragraphs = tree.xpath('//p/text()')
print('标题:', title)
print('段落:')
for p in paragraphs:print(p)