使用BeautifulSoup仅删除特定的HTML表格标签

0 投票
2 回答
2109 浏览
提问于 2025-04-20 10:53

我正在使用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 个回答

-1

你可以查看这个链接: 在Python中解析HTML标题标签的正则表达式模式

你需要根据自己的需求调整下面的内容,来自那个链接:

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

然后遍历它们。或者你也可以使用正则表达式,就像那个链接里建议的那样。

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

补充说明:修正了列表推导式,从soup中提取文本。

撰写回答