【问题标题】:How to extract text from between html tags?如何从html标签之间提取文本?
【发布时间】:2018-11-22 10:41:33
【问题描述】:

我有一些 html 元素,我想从中提取文本。所以html 就像

<pre>
<span class="ansi-red-fg">ZeroDivisionError</span>Traceback (most recent call last)
<span class="ansi-green-fg">&lt;ipython-input-2-0f9f90da76dc&gt;</span> in <span class="ansi-cyan-fg">&lt;module&gt;</span><span class="ansi-blue-fg">()</span>

</pre>

我想将文本提取为

ZeroDivisionErrorTraceback (most recent call last)
<ipython-input-2-0f9f90da76dc> in<module>()

我找到了该问题的答案here,但它对我不起作用。完整的示例代码

from bs4 import BeautifulSoup as BSHTML

bs = BSHTML("""<pre>
<span class="ansi-red-fg">ZeroDivisionError</span>Traceback (most recent call last)
<span class="ansi-green-fg">&lt;ipython-input-2-0f9f90da76dc&gt;</span> in <span class="ansi-cyan-fg">&lt;module&gt;</span><span class="ansi-blue-fg">()</span>
</pre>""")
print bs.font.contents[0].strip()

我得到以下错误:

Traceback (most recent call last):
  File "invest.py", line 13, in <module>
    print bs.font.contents[0].strip()
AttributeError: 'NoneType' object has no attribute 'contents'

我缺少什么吗? beautifulsoap的版本:4.6.0

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    您想要pre 块的所有文本内容吗?

    print bs.pre.text
    

    返回:

    ZeroDivisionErrorTraceback (most recent call last)
    <ipython-input-2-0f9f90da76dc> in <module>()
    

    【讨论】:

    • 啊完美!谢谢
    • 但这不是获取每个文本的通用解决方案,无论我有什么标签......
    • 什么意思?
    • 当我没有pre 标签时,您的方法将不起作用。我不关心标签,我只想要封闭的文字。如果它们包含在prefont 或其他任何地方。我不在乎周围有什么标签。我只想要附上的文字...
    • 那么就做bs.text
    【解决方案2】:

    您的代码示例中的.font 指的是HTML 标记&lt;font&gt;。由于您正在查看文档中的所有文本,因此您可以使用以下内容:

    contents = bs.find_all(text=True)
    for c in contents:
        print(c)  # replace this with whatever you're trying to do
    

    输出:

    ZeroDivisionError
    Traceback (most recent call last)
    
    <ipython-input-2-0f9f90da76dc>
     in
    <module>
    ()
    

    当前bs.fontNone,因为您正在解析一个不包含任何&lt;font&gt; 标记的文档。

    如果您只想将内容作为一个长字符串,您可以通过使用 bs.text 来获得它

    '\nZeroDivisionErrorTraceback (most recent call last)\n<ipython-input-2-0f9f90da76dc> in <module>()\n'
    

    【讨论】:

    • 不太好用。我没听懂Traceback (most recent call last)...
    • 另外,它不保留新行!
    • 啊,我明白我误解了你的文件。编辑以获取所有内容(并保留换行符)。
    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多