zl程序教程

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

当前栏目

Python HTML页面解析大全之如何使用xpath从页面提取信息wwdc2022并输出为markdown和excel

PythonExcel输出HTML 如何 解析 信息 页面
2023-09-11 14:18:32 时间

很多时候我们需要从网页中提取信息,本文将以wwdc2022年页面中提取核心信息为例,为大家展示如何使用python提取信息并输出为markdown或excel。文章底部有完整代码和测试文件

python读取html文件

import codecs
f=codecs.open("wwdc2022.html", 'r')
h = f.read()

也可以使用with方式

with open("test.html", "r", encoding='utf-8') as f:
    text= f.read()

使用xpath提取数据

引入库

from lxml import html
import requests

将html文件专为html

tree = html.fromstring(h) 

提取文件

# Get element using XPath
sessions = tree.xpath('//*[@id="sessions"]/section[2]')
print(sessions)

多数据提取

获取多少个section

sectionLen = len(tree.xpath('//*[@id="sess