问题描述
让我们说这是我的XML
<sky class="new">
<list name="school">
<p>63</p>
<p>62</p>
<p>61</p>
</list>
</sky>
这是我在列表中的值。
value = [51,56,87]
现在我需要的是:
<sky class="new">
<list name="school">
<p>51</p>
<p>56</p>
<p>87</p>
</list>
</sky>
到目前为止我想要做的是:
for i in soup.find_all('sky',{'class':'new'}):
k = i.find('list',{'name':'school'})
在此之后我不知道该怎么办,您能在这里帮忙吗?
EDIT1:
<sky class="new">
<list name="alpha">
<item>
<p unit="kg">63</p>
<p weight="wg">54</p>
</item>
<item>
<p unit="kg">57</p>
<p weight="wg">32</p>
</item>
</list>
</sky>
我无法为<p unit="kg"></p>
制作图案
解决方法
另一个版本:
from bs4 import BeautifulSoup
txt = '''<sky class="new">
<list name="school">
<p>63</p>
<p>62</p>
<p>61</p>
</list>
</sky>'''
soup = BeautifulSoup(txt,'xml')
values = [51,56,87]
for p,new_value in zip(soup.select('sky.new > list[name="school"] > p'),values):
p.string = str(new_value)
print(soup)
打印:
<?xml version="1.0" encoding="utf-8"?>
<sky class="new">
<list name="school">
<p>51</p>
<p>56</p>
<p>87</p>
</list>
</sky>
,
尝试这样的事情:
targets = soup.select('p')
for target in targets:
repl = str(value[targets.index(target)])
target.string.replace_with(repl)
soup
输出:
<html><body><sky class="new">
<list name="school">
<p>51</p>
<p>56</p>
<p>87</p>
</list>
</sky></body></html>