如何将这个 for 循环放入定义中?
from bs4 import BeautifulSoup
html="<p>ABC <i>Italic1 </i><i>Italic2</i></p>"
soup = BeautifulSoup(html,"html.parser")
for i in soup.findAll('i'):
soup.i.unwrap()
print(soup)
我试过了,但没有成功:
def UnwrapTag(x):
x=str(x)
for x in soup.findAll(x):
soup.x.unwrap() #wrong but what else?
UnwrapTag('i')
请您参考如下方法:
嗯,实际上你不应该使用 soup.i在这里。
soup.i表示第一个<i> soup 内的元素变量。
只是因为您使用了相同的名称 - 它起作用了。您实际想要使用的是 i变量(而不是 soup.i )。
from bs4 import BeautifulSoup
html="<p>ABC <i>Italic1 </i><i>Italic2</i></p>"
soup = BeautifulSoup(html,"html.parser")
for i in soup.findAll('i'):
i.unwrap()
print(soup)
这里也一样:
def UnwrapTag(x):
x=str(x)
for x in soup.findAll(x):
x.unwrap()
UnwrapTag('i')
