【问题标题】:How to extract text from between the <br> tags in BeautifulSoup如何从 BeautifulSoup 中的 <br> 标签之间提取文本
【发布时间】:2020-04-08 06:16:36
【问题描述】:

我要做的是只从&lt;td&gt; 元素中抓取公司名称,该元素有多个&lt;br&gt; 标签。仅供参考,一些&lt;td&gt; 有一个公司名称,而另一些有两个。请参阅下面的&lt;td&gt; 元素:

<td id="MainContent_DisassociatedRegistrationsCell" colspan="2">
<p style="background-color:#CCCCCC;width:100%;text-align:center">
<strong>License #: 
<a href="LicenseDetail.aspx?LicNum=332673">332673</a>
</strong>
</p>
BAY AREA REMODELING CO
<br>
5230 EAST 12TH
<br>
OAKLAND, CA 94601
<br>
<strong>Effective Dates:</strong>
09/16/1982 - 06/30/1984
<p style="background-color:#CCCCCC;width:100%;text-align:center">
<strong>License #: 
<a href="LicenseDetail.aspx?LicNum=377133">377133</a>
</strong>
</p>
SAVAGE ROOFING COMPANY
<br>
3055 ALVARADO STREET
<br>
SAN LEANDRO, CA 94577
<br>
<strong>Effective Dates:</strong>
 07/01/1982 - 03/31/1985
</td>

所以从上面的&lt;td&gt; 元素,我想要输出:

BAY AREA REMODELING CO
SAVAGE ROOFING COMPANY

【问题讨论】:

    标签: python web-scraping beautifulsoup line-breaks


    【解决方案1】:

    找到需要的p标签后使用next_sibling

    例如:

    from bs4 import BeautifulSoup
    
    html = """<td id="MainContent_DisassociatedRegistrationsCell" colspan="2">
    <p style="background-color:#CCCCCC;width:100%;text-align:center">
    <strong>License #: 
    <a href="LicenseDetail.aspx?LicNum=332673">332673</a>
    </strong>
    </p>
    BAY AREA REMODELING CO
    <br>
    5230 EAST 12TH
    <br>
    OAKLAND, CA 94601
    <br>
    <strong>Effective Dates:</strong>
    09/16/1982 - 06/30/1984
    <p style="background-color:#CCCCCC;width:100%;text-align:center">
    <strong>License #: 
    <a href="LicenseDetail.aspx?LicNum=377133">377133</a>
    </strong>
    </p>
    SAVAGE ROOFING COMPANY
    <br>
    3055 ALVARADO STREET
    <br>
    SAN LEANDRO, CA 94577
    <br>
    <strong>Effective Dates:</strong>
     07/01/1982 - 03/31/1985
    </td>"""
    
    soup = BeautifulSoup(html, 'html.parser')
    for p in soup.find_all('p'):
        print(p.next_sibling.strip())  
    

    输出:

    BAY AREA REMODELING CO
    SAVAGE ROOFING COMPANY
    

    【讨论】:

      【解决方案2】:

      使用BeautifulSoup

      >>> from bs4 import BeautifulSoup
      >>> soup = BeautifulSoup(html, "html.parser")
      >>> [p.next_sibling.strip() for p in soup.findAll("p")]
      ['BAY AREA REMODELING CO', 'SAVAGE ROOFING COMPANY']
      

      【讨论】:

      • 谢谢伙计.. 效果很好。理解真的很有用。
      • 不客气!记得点赞也是为了感谢贡献;)
      • 我当然知道先生,我已经这样做了,但是那些声誉
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2022-11-19
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多