Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.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 如何使用BeautifulSoup更改标签名?_Python_Html Parsing_Beautifulsoup - Fatal编程技术网

Python 如何使用BeautifulSoup更改标签名?

Python 如何使用BeautifulSoup更改标签名?,python,html-parsing,beautifulsoup,Python,Html Parsing,Beautifulsoup,我正在使用python+BeautifulSoup解析HTML文档 现在我需要用替换HTML文档中的所有元素 如何在不更改文档中任何其他内容的情况下更改标记名?来自 从美化组导入美化组,标记 汤=美丽的汤(“文本在此”) tag=tag(汤,“h1”[(“类”、“某些类”)])) 标记.插入(0,“文本此处”) 汤。h2。替换为(标记) 印花汤 #文本此处 我不知道您是如何访问标签的,但以下内容对我有用: import BeautifulSoup if __name__ == "__main_

我正在使用python+BeautifulSoup解析HTML文档

现在我需要用
替换HTML文档中的所有
元素

如何在不更改文档中任何其他内容的情况下更改标记名?

来自

从美化组导入美化组,标记
汤=美丽的汤(“文本在此”)
tag=tag(汤,“h1”[(“类”、“某些类”)]))
标记.插入(0,“文本此处”)
汤。h2。替换为(标记)
印花汤
#文本此处

我不知道您是如何访问
标签的,但以下内容对我有用:

import BeautifulSoup

if __name__ == "__main__":
    data = """
<html>
<h2 class='someclass'>some title</h2>
<ul>
   <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
   <li>Aliquam tincidunt mauris eu risus.</li>
   <li>Vestibulum auctor dapibus neque.</li>
</ul>
</html>

    """
    soup = BeautifulSoup.BeautifulSoup(data)
    h2 = soup.find('h2')
    h2.name = 'h1'
    print soup
如您所见,
h2
变成了
h1
。文档中的其他内容没有改变。我正在使用Python2.6和Beautifulsoup3.2.0

如果您有多个
h2
,并且希望全部更改,您可以简单地执行以下操作:

soup = BeautifulSoup.BeautifulSoup(your_data)
while True: 
    h2 = soup.find('h2')
    if not h2:
        break
    h2.name = 'h1'
只是:

tag.name = 'new_name'

我不知道为什么它以前对我不起作用。谢谢你的回答。我想这将删除h2标签的所有内容。我只想替换标签名,并保留所有其他内容不变。
soup = BeautifulSoup.BeautifulSoup(your_data)
while True: 
    h2 = soup.find('h2')
    if not h2:
        break
    h2.name = 'h1'
tag.name = 'new_name'