Skip to main content
 首页 » 编程设计

python之使用 python 删除 html 标签

2025年05月04日8yxwkf

我知道这方面可能有一百万个问题,但我想知道如何在不必导入或使用 HTMLParser 或正则表达式的情况下删除这些标签。我尝试了一堆不同的替换语句来尝试删除 < > 包围的部分字符串,但无济于事。

基本上我正在使用的是:

response = urlopen(url) 
html = response.read() 
html = html.decode() 

从这里开始,我只是试图操纵字符串变量 html 来执行上述操作。有什么方法可以按照我指定的方式进行,还是必须使用我以前见过的方法?

我还尝试制作一个 for 循环遍历每个字符以检查它是否被包含,但由于某种原因它不会给我正确的打印输出,即:

for i in html: 
    if i == '<': 
        html.replace(i, '') 
        delete = True 
    if i == '>': 
        html.replace(i, '') 
        delete = False 
    if delete == True: 
        html.replace(i, '') 

欢迎任何意见。

请您参考如下方法:

str.replace 返回字符串的副本,所有出现的子字符串都替换为新字符串,您不能像现在这样使用它,也不应该修改循环正在迭代的字符串。使用额外列表是您可以采用的方法之一:

txt = [] 
for i in html: 
    if i == '<': 
        delete = True 
        continue 
    if i == '>': 
        delete = False 
        continue 
    if delete == True: 
        continue 
 
    txt.append(i) 

现在 txt 列表包含结果文本,您可以加入它:

print ''.join(txt) 

演示:

html = '<body><div>some</div><div>text</div></body>' 
#... 
>>> txt 
['s', 'o', 'm', 'e', 't', 'e', 'x', 't'] 
>>> ''.join(txt) 
'sometext'