gpt4 book ai didi

python - 使用 Python 将 HTML 表格保存到 excel 中时出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:45 24 4
gpt4 key购买 nike

这是我第一次使用 Python,我正在尝试抓取方法并将网上可用的代码放在一起,目前我一直在将输出保存到 Excel 文件中。

好的,首先我需要阅读一封来自 Outlook 的电子邮件并获取其中的数据。但它是表格格式,这意味着创建者将 Excel 中的数据复制粘贴为表格,因此我发现的最佳方法是将其转换为 HTML 文件。

import win32com.client
import xlsxwriter
import pandas as pd
import requests
from bs4 import BeautifulSoup

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
'''message = messages.GetLast()
body_content = message.Body
subject = message.Subject
categories = message.Categories
print(body_content)
print(subject)
print(categories)'''
string = "Monthly PPM Report"
for message in messages:
if string in message.Subject:
print(message.HTMLBody)
Html_file= open("filename.html","w", encoding="utf-8")
Html_file.write(message.HTMLBody)
Html_file.close()

因此,使用上面的代码,我设法将电子邮件保存为 HTML 文件。下一步是找到以 div 类为目标的表格。

rfile  = open('filename.html')
rsoup = BeautifulSoup(rfile)
nodes1 = rsoup.find('div',{'class':'MsoNormalTable'})

当我尝试打印时,我设法获得了我需要的表格,但是当我尝试使用 nodes1.to_excel('test.xlsx') 将其保存为 Excel 文件时,我收到此错误.

nodes1.to_excel('test.xlsx') AttributeError: 'NoneType' object has noattribute 'to_excel'

关于我缺少哪一步的任何建议?

最佳答案

要使用 pandas to_excel() 方法,您首先需要一个 pandas DataFrame

假设 nodes1 是一个字典对象:

data_frame = pd.DataFrame(data=nodes1)
data_frame.to_excel('label_name')

关于python - 使用 Python 将 HTML 表格保存到 excel 中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com