【发布时间】:2020-01-27 14:29:53
【问题描述】:
我在下载的 html 文件以适当的格式解析时遇到了挑战。 在 div DIV id=article_participants class="content_part hid" 中,有一些高管的名字(例如 Dror Ben Asher、Ori Shilo 和 Guy Goldberg): 所以每个html页面的执行者不同,但是div和html的设置是一样的。
<DIV id=article_participants class="content_part hid">
<P>Redhill Biopharma Ltd. (NASDAQ:<A title="" href="http://seekingalpha.com/symbol/rdhl" symbolSlug="RDHL">RDHL</A>)</P>
<P>Q4 2014 <SPAN class=transcript-search-span style="BACKGROUND-COLOR: yellow">Earnings</SPAN> Conference <SPAN class=transcript-search-span style="BACKGROUND-COLOR: #f38686">Call</SPAN></P>
<P>February 26, 2015 9:00 AM ET</P>
<P><STRONG>Executives</STRONG></P>
<P>Dror Ben Asher - CEO</P>
<P>Ori Shilo - Deputy CEO, Finance and Operations</P>
<P>Guy Goldberg - Chief Business Officer</P>
<P><STRONG>Analysts</STRONG></P>
<p>Scott Henry - Roth Capital</p>
</div>
稍后在 html 中(在 DIV id=article_qanda class="content_part hid")中,高管们正在回答问题。这些答案(被<P><STRONG><SPAN class=answer>Ori Shilo</SPAN></STRONG></P>识别)
在 Dropbox 中我分享了我下载的一个 html 示例:https://www.dropbox.com/s/uka24w7o5006ole/transcript-86-855.html?dl=0
我的输出应该是以下内容(对于一个 csv 文件中目录中的所有文件): 高管 /// 答案 /// html 的标题
到目前为止,我的代码仅适用于一位 CEO:
import textwrap
import os
from bs4 import BeautifulSoup
directory ='C:/Research syntheses - Meta analysis/SeekingAlpha/'
for filename in os.listdir(directory):
if filename.endswith('.html'):
fname = os.path.join(directory,filename)
with open(fname, 'r') as f:
soup = BeautifulSoup(f.read(),'html.parser')
print('{:<30} {:<70}'.format('Name', 'Answer'))
print('-' * 101)
def find_executive(soup, executive):
for answer in soup.select(f'p:contains("Question-and-Answer Session") ~ strong:contains({executive}) + p'):
txt = answer.get_text(strip=True)
s = answer.find_next_sibling()
while s:
if s.name == 'strong' or s.find('strong'):
break
if s.name == 'p':
txt += ' ' + s.get_text(strip=True)
s = s.find_next_sibling()
txt = ('\n' + ' '*31).join(textwrap.wrap(txt))
print('{:<30} {:<70}'.format(func, txt), file=open("output.txt", "a"))
有人可以帮我解决这个挑战吗?
【问题讨论】:
-
这能回答你的问题吗? Parse div element
-
很遗憾没有。
标签: python beautifulsoup