【问题标题】:Using beautifulsoup to separate strings separated by `<br>`使用beautifulsoup 分隔由`<br>` 分隔的字符串
【发布时间】:2018-09-06 03:44:25
【问题描述】:

我想从使用&lt;br&gt; 的网站获取一些数据。在使用 beautifulsoup4 解析的 html 中,有时我有以下模式:

"<p class=some_class>text_1. text_2 (text_3<span class=GramE>)</span> 
<br> 
text_4,<span style='mso-fareast-font-family:"Arial Unicode MS"'> 
</span>text_5.</p>"

但如果网站以更好的方式编写,它会看起来像:

"<p class=some_class>text_1. text_2(text_3<span class=GramE>)</span 
</p> <p class=some_class>
text_4,<span style='mso-fareast-font-family:"Arial Unicode MS"'> 
</span>text_5.</p>

要提取我想要的字符串,我会提取每个 &lt;p&gt; 中的所有文本。 但是,现在我要分隔的字符串由&lt;br&gt; 分隔。

我的问题如下:如何使用&lt;br&gt; 来解开我感兴趣的字符串部分?我的意思是,我想要[text_1.+text_2+text_3, text_4+text_5.] 之类的东西。

我明确询问&lt;br&gt; 的使用,因为它是我发现的唯一可以分隔我感兴趣的字符串的元素。此外,在网站的其他部分,我用&lt;br/&gt; 分隔我感兴趣的字符串,而不是&lt;br&gt;

我无法通过使用 replace() 函数来解决这个问题,因为我的对象是来自 bs4 的标签。此外,使用 bs4 中的 find("br") 会给我 "&lt;br/&gt;" 而不是我想要的文本。这样一来,question 中的答案就不是我想要的了。我认为一种方法是将标签从我必须的 bs4 转换为 html,然后使用 replace() 函数更改“&lt;br/&gt;”,最后将其转换回 bs4 元素。但是,我不知道如何进行此更改,并且我也想知道是否有更简单和更短的方法来执行此操作。

【问题讨论】:

    标签: html python-3.x beautifulsoup


    【解决方案1】:

    这是我找到的一个解决方案,但由于它不使用 bs4 的任何功能,因此它很长且效率低下。不过,它确实有效。

    html_doc = """
    "<p class=some_class>text_1. text_2 (text_3<span class=GramE>)</span> 
    <br> 
    text_4,<span style='mso-fareast-font-family:"Arial Unicode MS"'> 
    </span>text_5.</p>"
    """
    
    def replace_br(soup_object):
        html1=str(soup_object)
        html1=html1.replace("<br>", "</p> <p>")
        soup_html1 = BeautifulSoup(html1, 'html.parser')
        return soup_html1.find_all("p")
    
    replace_br(html_doc)
    [<p class="some_class">text_1. text_2 (text_3<span class="GramE">)</span>
    </p>, <p> 
    text_4,<span style='mso-fareast-font-family:"Arial Unicode MS"'>
    </span>text_5.</p>]
    

    【讨论】:

      最近更新 更多