zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python爬虫:使用lxml解析网页内容

Python爬虫 解析 网页内容 lxml 使用
2023-09-14 09:07:14 时间

安装

pip install lxml

代码示例


from lxml import etree

text = """
<html>
    <head>
        <title>这是标题</title>
    </head>
    <body>
        <div>这是内容</div>
    </body>
</html>"""

html = etree.HTML(text)

# 使用xpath解析
titles = html.xpath("//title")
for title in titles:
    print(title.text)

# 使用css解析
titles = html.cssselect("title")
for title in titles:
    print(title.text)