Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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 如何在beautiful soup中的现有字符串上添加标记_Python_Html_Parsing_Beautifulsoup_Tags - Fatal编程技术网

Python 如何在beautiful soup中的现有字符串上添加标记

Python 如何在beautiful soup中的现有字符串上添加标记,python,html,parsing,beautifulsoup,tags,Python,Html,Parsing,Beautifulsoup,Tags,我想在标记的两个节点之间应用下划线标记 original\u tag=正确答案是中国: 期望输出=正确答案是中国: 我试过这个 correctoptions = [x for x in correctoptions if x.name == "p"] for x in correctoptions: new_tag = soup.new_tag("u") x.strong.insert(0, new_tag) 这项工作: import cop

我想在标记的两个节点之间应用下划线标记

original\u tag=正确答案是中国:

期望输出=正确答案是中国:

我试过这个

correctoptions = [x for x in correctoptions if x.name == "p"]
for x in correctoptions:
   new_tag = soup.new_tag("u")
   x.strong.insert(0, new_tag)
这项工作:

import copy
from bs4 import BeautifulSoup

soup = BeautifulSoup("<p>The correct answer is <strong>China:</strong></p>", "html.parser")
# we modify soup object by 'append', so need to use a copy of it to find "strong" tag separately
soup_copy = copy.deepcopy(soup)
u_tag = soup.new_tag("u")
u_tag.append(soup_copy.find("strong"))
soup.find("strong").replaceWith(u_tag)

print(soup)

这提供了一个关于如何开始的总体思路,您可以根据需要修改上述逻辑。

我使用
soup.strong.wrap(soup.new_tag(“u”))解决了这个问题。
发布您的完整代码。或者至少是它的一个版本复制了这个问题。完成后,实际上没有错误,只有我的忽略检查我的答案。我在他的
递归错误中得到了这个错误错误:调用Python对象时超过了最大递归深度
我发布的代码工作得很好,注意使用soup,并尽可能接近我发布的代码。我使用
soup.strong.wrap(“u”)
,完成了相同的操作,谢谢您的帮助。我将签出
wrap
方法。您的意思是
soup.strong.wrap(soup.new_标记(“u”))
?您也应该接受此答案,以将问题标记为已解决。是的,我将在2天后接受,因为SO这么说
<p>The correct answer is <u><strong>China:</strong></u></p>