使用BeautifulSoup仅从HTML文件中删除特定的表标签

时间:2014-09-08 11:58:30

标签: python xml beautifulsoup

我正在使用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()!=""]))

2 个答案:

答案 0 :(得分:0)

这应该这样做。

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

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

答案 1 :(得分:-1)

您可以查看:regex pattern in python for parsing HTML title tags

您必须从该链接调整以下内容,以满足您的需求:

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

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

相关问题