【问题标题】:Convert to string untagged child Beautiful soup转换为字符串未标记的孩子 美丽的汤
【发布时间】:2018-09-08 05:45:34
【问题描述】:

我正在尝试使用 BeautifulSoup4 废弃一些 html 文档,但我一直在尝试废弃这个 div:

<div class="small-info" style="margin-top: 4px;">
                5
                 <sup>th</sup>  
                August 2018
</div>

我想获得“2018 年 8 月 5 日”,我该怎么做?

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您必须使用get_text() 并删除多余的空格

    html="<div class='small-info' style='margin-top: 4px;''>5<sup>th</sup>August 2018</div>"
    soup=BeautifulSoup(html,"lxml")
    div=soup.find("div",{"class","small-info"})
    text=div.get_text().replace("  ","")
    
    #text : 5 th August 2018
    

    【讨论】:

    • 它工作了,但是 get_text().replace(" ","") 是如何工作的?我不明白。如何跳过 sup 标签
    • get_text() 返回 div 中的字符串。 replace 就是去掉多余的空格,什么都不替换
    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 2014-09-03
    • 2011-10-26
    • 1970-01-01
    相关资源
    最近更新 更多