Python 将 html 文档 表格 转 为 JSON 格式

3 篇文章 0 订阅
3 篇文章 0 订阅

Python 将 html 文档 表格 转 为 JSON 格式
测试示例:

import requests
from lxml import etree
import pandas as pd

url = "http://xxx"

header = {
    "Cookie": "xxx"
}
res = requests.get(url, headers=header)
doc = etree.HTML(res.text)

columns = doc.xpath('/html/body/div/div[2]/div/div[2]/table/thead/tr/th/text()')
data = doc.xpath('/html/body/div/div[2]/div/div[2]/table/tbody/tr')
# print(columns)
# print(data)
df = pd.DataFrame(columns=columns)


def trans_value(pe, path: str) -> str:
    if type(pe.xpath(path)) is list and len(pe.xpath(path)) == 1:
        return str(pe.xpath(path)[0])
    else:
        return ''


for row in data:
    td = row.xpath('./td')
    # print(td)
    temp = []
    for td_row in td:
        # print(td_row.xpath('./*'))
        a = td_row.xpath('./a')
        if a != [] and a[0].xpath('./text()') == ['修改']:
            # temp.append(transValue(a[0], './@href'))
            temp.append('')
            continue
        if a != [] and a[0].xpath('./text()') == ['播放']:
            audio_tl = trans_value(a[0], './@onclick').replace("'", '').split(',')
            if len(audio_tl) == 3:
                temp.append(audio_tl[1])
            else:
                temp.append('')
            continue
        temp.append(trans_value(td_row, './text()'))
    # print(temp)
    df.loc[len(df)] = temp
# df.to_excel('out.xlsx', index=False)
with open('out.json', 'w', encoding='utf8') as f:
    f.write(df.to_json(orient='records', force_ascii=False))

print('处理完成')
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值