Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python删除html标记?_Python - Fatal编程技术网

使用python删除html标记?

使用python删除html标记?,python,Python,我知道在这方面可能有一百万个问题,但我想知道如何在不必导入或使用HTMLParser或regex的情况下删除这些标记。我尝试了一系列不同的replace语句,试图删除由括起的字符串的一部分,但没有成功 基本上我的工作是: response = urlopen(url) html = response.read() html = html.decode() 从这里开始,我只是尝试操作字符串变量html来完成上述操作。有没有办法按照我指定的方式来做,或者你必须使用我以前见过的方法 我还尝试创建一个

我知道在这方面可能有一百万个问题,但我想知道如何在不必导入或使用HTMLParser或regex的情况下删除这些标记。我尝试了一系列不同的replace语句,试图删除由<>括起的字符串的一部分,但没有成功

基本上我的工作是:

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, '')
html中的i的
:
如果i='':
html.replace(i,,)
delete=False
如果delete==True:
html.replace(i,,)

非常感谢您的任何输入。

str.replace
返回一个字符串副本,其中所有出现的子字符串都被new替换,您不能像使用它那样使用它,并且您不应该修改循环正在其上迭代的字符串。使用额外列表是您可以使用的方法之一:

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

    txt.append(i)
演示:

html='sometext'
#...
>>>文本
['s','o','m','e','t','e','x','t']
>>>''.join(txt)
“sometext”

请不要使用正则表达式解析HTML。如果不需要导入或使用HTMLPasser或regex,它将无法工作,请参阅以获得有趣的解释。你为什么给自己这么愚蠢的限制。谢谢,我一直在寻找一种方法来做到这一点,而不必使用一些预先实现的方法,因为我没有从中真正学到任何东西。
print ''.join(txt)
html = '<body><div>some</div><div>text</div></body>'
#...
>>> txt
['s', 'o', 'm', 'e', 't', 'e', 'x', 't']
>>> ''.join(txt)
'sometext'