首页 > 解决方案 > 重新格式化 Beautiful Soup 输出以包含 CSS

问题描述

我正在尝试解析电子邮件文本以使用 Python 加快我的工作流程。我首先保存的电子邮件在我的本地驱动器上有一个 .htm。然后,我想尝试使用 Jupyter Notebook 从电子邮件中的表格中提取某些信息。每当我创建汤时,结果都是一个间隔的文本字段。我无法使用此汤进行适当的 HTML 调用以提取数据。我怎样才能重新格式化汤?

.htm 文件已经是文本,但我仍然想使用 Beautiful Soup 来帮助我解析文本字段。我应该尝试不同的解析方法吗?

from bs4 import BeautifulSoup
raw_file = open(r"C:\Users\Desktop\Example.htm").read()
soup = BeautifulSoup(raw_file, 'lxml')
print(soup)

我期望一个格式很好的汤文件,相反,这是 print 语句返回的内容:

<html><body>
<p>ÿþh t m l   x m l n s : v = " u r n : s c h e m a s - m i c r o s o f t - c o m : v m l " 

 x m l n s : o = " u r n : s c h e m a s - m i c r o s o f t - c o m : o f f i c e : o f f i c e " 

 x m l n s : w = " u r n : s c h e m a s - m i c r o s o f t - c o m : o f f i c e : w o r d " 

 x m l n s : m = " h t t p : / / s c h e m a s . m i c r o s o f t . c o m / o f f i c e / 2 0 0 4 / 1 2 / o m m l " 

 x m l n s = " h t t p : / / w w w . w 3 . o r g / T R / R E C - h t m l 4 0 " &gt; 





 h e a d &gt; 

 m e t a   h t t p - e q u i v = C o n t e n t - T y p e   c o n t e n t = " t e x t / h t m l ;   c h a r s e t = u n i c o d e " &gt; 

 m e t a   n a m e = P r o g I d   c o n t e n t = W o r d . D o c u m e n t &gt; 

 m e t a   n a m e = G e n e r a t o r   c o n t e n t = " M i c r o s o f t   W o r d   1 5 " &gt; 

 m e t a   n a m e = O r i g i n a t o r   c o n t e n t = " M i c r o s o f t   W o r d   1 5 " &gt; 


 b a s e

当我打电话时——

print(raw_file)

以下返回:

ÿþ<html xmlns:v="urn:schemas-microsoft-com:vml"

xmlns:o="urn:schemas-microsoft-com:office:office"

xmlns:w="urn:schemas-microsoft-com:office:word"

xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"

xmlns="http://www.w3.org/TR/REC-html40">



<head>

<meta http-equiv=Content-Type content="text/html; charset=unicode">

<meta name=ProgId content=Word.Document>

<meta name=Generator content="Microsoft Word 15">

<meta name=Originator content="Microsoft Word 15">

<base

标签: pythonparsingbeautifulsouplocalhosthtml-email

解决方案


推荐阅读