【问题标题】:Parse html files with variable element解析带有可变元素的 html 文件
【发布时间】: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")中,高管们正在回答问题。这些答案(被&lt;P&gt;&lt;STRONG&gt;&lt;SPAN class=answer&gt;Ori Shilo&lt;/SPAN&gt;&lt;/STRONG&gt;&lt;/P&gt;识别)

在 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"))

有人可以帮我解决这个挑战吗?

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

您可以尝试以下方法:

在下面的代码中,将'html_folder' 替换为您的html files folder path

from pathlib import Path
from bs4 import BeautifulSoup as bs

def get_names(fname):
    with open(fname, 'r') as f:
        soup = bs(f.read())
        names = soup.select('div#article_participants > p')
        return [x.text for x in names]
    return []

html_files = list(map(str, Path('html_folder').rglob('*.html')))
for f in html_files:
    print(get_names(f))

【讨论】:

  • 您是否有建议查找您提供的输出中提到的高管,并在名为 (DIV id=article_qanda class="content_part hid") 的 html 文件部分中用作搜索元素,以及比他们给出的答案?
【解决方案2】:

@abhilb 但这仅给出了 div#article_participants 的结果。我需要的是您提供的输出中提到的高管,并在名为 (DIV id=article_qanda class="content_part hid") 的 html 文件部分中用作搜索元素,而不是他们给出的答案。

['Banco Latinoamericano de Comercio Exterior, S.A (NYSE:BLX)', 'Q2 2014 Earnings Call', 'July 24, 2014 11:00 am ET', 'Executives', 'Rubens V. Amaral - Chief Executive Officer, President and Director', 'Christopher Schech - Chief Financial Officer and Executive Vice President of Finance ', 'Analysts', 'Yuri R. Fernandes - JP Morgan Chase & Co, Research Division']
['Redhill Biopharma Ltd. (NASDAQ:RDHL)', 'Q4 2014 Earnings Conference Call', 'February 26, 2015 9:00 AM ET', 'Executives', 'Dror Ben Asher - CEO', 'Ori Shilo - Deputy CEO, Finance and Operations', 'Guy Goldberg - Chief Business Officer', 'Analysts', 'Scott Henry - Roth Capital', 'Vernon Bernardino - MLV', 'Ramakanth Swayampakula - H.C. Wainwright']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 2020-06-22
    • 2015-01-03
    • 2023-01-04
    相关资源
    最近更新 更多