【问题标题】:Remove only specific table tags from HTML files using BeautifulSoup使用 BeautifulSoup 从 HTML 文件中仅删除特定的表格标签
【发布时间】:2014-11-01 15:25:02
【问题描述】:

我正在使用 BeautifulSoup 包解析数百个 HTML 文档。我的代码能够很好地解析整个文档。

我想根据条件删除所有表格标签的内容。由于很少有表格(根据 HTML 标记)实际上可能不是表格,而是表格内呈现的文本。如果表格的内容中超过 75% 的字符为数字,我想把它当作实际的表格并删除它,否则我想保留它。

我是 Python 新手,不确定如何仅删除特定表的全部内容。

假设我的 HTML 文档是:

<document>
<table>
100
</table>
<text>
Hello Word
</text>
<table>
Test
</table>
</document>

以下代码将生成整个 HTML 文档的内容,即

100
Hello Word 
Test 

我想要的是:

Hello Word 
Test 

请注意,代码还包含一个用于检查文本是否有用的函数。我分别计算字母和数字字符,因为可能有很多空格和其他乱码。

请帮助我删除无用的表格,即包含超过 75% 的数字字符。另请注意,表不必是文档的直接子级。

from bs4 import BeautifulSoup
import html5lib
def isTableUseful(text): #Returns True if table is to be included
    try:
        countAlpha = 0
        countNumeric = 0
        for char in text:
            if char.isalpha():
                countAlpha += 1
            if char.isnumeric():
                countNumeric += 1
        FracNumeric = countNumeric/(countNumeric+countAlpha)
        return FracNumeric < 0.75
    except:
        return False
soup = BeautifulSoup("<document><table>100</table><text>Hello Word</text><table>Test</table></document>", "html5lib")
print ('\n'.join([e.encode("utf-8") for e in soup.recursiveChildGenerator() if isinstance(e,unicode) and e.strip()!=""]))

【问题讨论】:

    标签: python xml beautifulsoup


    【解决方案1】:

    应该这样做。

    def should_remove(text):
        count_number = 0
        for c in text:
            if c.isnumeric():
                count_number = count_number + 1    
        return count_number / len(text) > 0.75
    
    # TODO: Initialize soup
    
    # Remove all undesired tags from soup.
    [s.extract() for s in soup.find_all('table') if should_remove(s.get_text().strip())]
    
    #  Extract, format and print remaining text in soup.
    # in Python3
    [print(s.strip()) for s in soup.get_text().split('\n') if s.strip() != '']
    
    # OR in Python2: 
    result = [s.strip() for s in soup.get_text().split('\n') if s.strip() != '']
    for line in result:
        print line
    

    编辑:更正列表理解,从汤中提取文本。

    【讨论】:

    • @mhi..不幸的是,您的代码中删除所有不需要的标签的语句似乎无法正常工作。我得到 [u'100Hello WordTest'] 作为输出。
    • @Ankit 如果没有关于您当前正在运行的代码的更多信息,我很难提供帮助。我发布的代码在 python 3.4.1 上运行良好。
    • 我使用的是 Python 2.7.5。
    • 如果这个答案解决了你的问题,请采纳。
    • @mhi..上面的代码没有解决我的问题。 find_all('table') 将仅搜索表格标签。我需要的是来自表格标签的内容,这些内容本质上是文本的,以及来自其他标签的文本(如我的问题中所述)。不幸的是,我拥有的文件非常凌乱且非常大(~25-50 MB)。有很多标签没有关闭,这给任何内置解析器带来了问题,包括 HTML、XML、LXML。我想不出比手动完成并编写自己的函数更好的解决方案了。
    【解决方案2】:

    你可以查看这个:regex pattern in python for parsing HTML title tags

    您必须通过该链接在下面进行调整以满足您的需求:

    title = soup.find('title').text
    

    然后遍历它们。 或者您也可以按照该链接的建议执行正则表达式。

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 2020-10-27
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多