【问题标题】:Getting just the top level text in an HTML Tag仅获取 HTML 标记中的顶级文本
【发布时间】:2020-04-13 17:28:03
【问题描述】:

首先,我使用 Python 和 Selenium 以及一些 BeautifulSoup 进行网页抓取。也许他们不能一起工作,但到目前为止我都无法解决这个特殊问题。我不相信它以任何方式超出了人类的智慧,但它超出了我的努力。

这里是 HTML:

<div class="summary">
            <div class="headingDate">09 January 2020 18:45 </div>
            <div class="callout"><span class="grey">Bob Smith</span>Student of the Week - JANUARY </div>


        </div>

        <div class="body">
            January 2020

                <div class="boxContent">                    


<div class="third-small">
    <div class="dropzone drop-smaller dz-clickable" id="d-3d3361e5-1e47-403c-a6b5-10137143f994">
        <div class="dz-message" data-dz-message="">
            <p class="centre"><i class="far fa-image biggest"></i></p>
            <p class="centre">Drag and drop file here to attach</p>
            <span class="bigLink"><i class="fa fa-upload"></i> Or choose file</span>
        </div>

实际的 HTML 更多。基本上,“body”标签非常大,包含“third-small”和其他类似项目。

我的问题似乎很简单:我想从 body 标签中单独获取“2020 年 1 月”。但我一直无法做到。如果我使用 BeautifulSoup 的“gettext”,它会让我获得所有其他包含的文本(如“将文件拖放到此处附加”),而没有明显的分离方式。是的,有一些换行符,但上面的文字中也有一些换行符,所以我觉得这不是一种安全的方式。我还使用了 BeautifulSoup 中的“find_all”,但这只是让我得到了所有包含的标签,其中不包括文本。

有办法吗?我也尝试过使用 Selenium 方法,但没有运气。

【问题讨论】:

    标签: python selenium web-scraping beautifulsoup


    【解决方案1】:
    from bs4 import BeautifulSoup
    html = """
    <div class="summary">
                <div class="headingDate">09 January 2020 18:45 </div>
                <div class="callout"><span class="grey">Bob Smith</span>Student of the Week - JANUARY </div>
    
    
            </div>
    
            <div class="body">
                January 2020
    
                    <div class="boxContent">                    
    
    
    <div class="third-small">
        <div class="dropzone drop-smaller dz-clickable" id="d-3d3361e5-1e47-403c-a6b5-10137143f994">
            <div class="dz-message" data-dz-message="">
                <p class="centre"><i class="far fa-image biggest"></i></p>
                <p class="centre">Drag and drop file here to attach</p>
                <span class="bigLink"><i class="fa fa-upload"></i> Or choose file</span>
            </div>
    """
    
    
    soup = BeautifulSoup(html, 'html.parser')
    
    print(soup.find("div", class_="body").contents[0].strip())
    

    输出:

    January 2020
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-27
      • 2019-11-10
      • 1970-01-01
      • 2011-08-07
      • 2014-07-22
      • 1970-01-01
      • 2011-06-09
      • 2011-12-27
      相关资源
      最近更新 更多