【发布时间】:2020-05-03 16:54:24
【问题描述】:
我是 Python 和 Panda 的新手,但我想从多个下载的文件(格式相同)中进行解析。 在每个 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>
在文件中还有一个名为“DIV id=article_qanda class="content_part hid”的部分,其中像 Ori Shilo 这样的高管被命名,后面跟着一个答案,比如:
<P><STRONG><SPAN class=answer>Ori Shilo</SPAN></STRONG></P>
<P>Good morning, Vernon. Both safety which is obvious and fertility analysis under the charter of the data and safety monitoring board will be - will be on up.</P>
到目前为止,我只成功地使用了一个 html 解析器,按姓名收集了一个人的所有答案。我不确定如何继续并将代码基于可变的高管列表。有人有什么建议吗?
import textwrap
import os
from bs4 import BeautifulSoup
directory ='C:/Research syntheses - Meta analysis/SeekingAlpha/out'
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)
for answer in soup.select('p:contains("Question-and-Answer Session") ~ strong:contains("Dror Ben Asher") + 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('Dror Ben Asher - CEO', txt), file=open("output.txt", "a"))
【问题讨论】:
-
我认为你已经在路上了,你的第一次尝试看起来不错。您将希望用参数替换代码的硬编码部分。 Functions 将成为您的朋友。关于您的实际问题,SO 并不意味着作为代码编写服务,所以请尽力而为,当您遇到困难时,我们会在这里提供帮助。见How to Ask 和What is On-Topic
-
我阅读了您发布的功能链接,但我不明白如何让我的高管被“功能”找到和使用。你能举个例子吗?当然,我不希望这是一个代码编写服务。