Python PyQuery如何将元素追加并重命名到其每个子元素中

Python PyQuery如何将元素追加并重命名到其每个子元素中,python,xml-parsing,pyquery,Python,Xml Parsing,Pyquery,如何将类属性附加或插入到其子元素中,但仅针对直接子元素,然后对下一个类和子元素重复该属性 在文档中,此处引用了它 我建议您使用。它在这样的任务上做得很好 from bs4 import BeautifulSoup soup = BeautifulSoup(YOUR_HTML_HERE, 'html.parser') for race in soup.find_all('race'): raceid = race['id'] # recursive=False because yo

如何将类属性附加或插入到其子元素中,但仅针对直接子元素,然后对下一个类和子元素重复该属性

在文档中,此处引用了它

我建议您使用。它在这样的任务上做得很好

from bs4 import BeautifulSoup
soup = BeautifulSoup(YOUR_HTML_HERE, 'html.parser')
for race in soup.find_all('race'):
    raceid = race['id']
    # recursive=False because you said you only want direct children.
    # omit recursive=False if you want all nomination tags within each race.
    for nomination in race.find_all('nomination', recursive=False):
        nomination['raceid'] = raceid
print(soup.prettify("latin-1"))

您就完成了。

您可以遍历所有
种族
标记,获取
id
,并将其添加到
提名

d = pq(html)
for race_el in d('race'):
    race = pq(race_el)
    race_id = race.attr('id')

    # get the nominations and add the attribute

    for nom_el in race.items('nomination'):
        pq(nom_el).attr('raceid', race_id)
<race id="211911"
<nomination raceid="211911" number="1" saddlecloth="1" horse="Prized Icon" id="198206" idnumber=""
...
<nomination raceid="211911" number="4" saddlecloth="4" horse="Crown Him" id="202278" idnumber=""
from bs4 import BeautifulSoup
soup = BeautifulSoup(YOUR_HTML_HERE, 'html.parser')
for race in soup.find_all('race'):
    raceid = race['id']
    # recursive=False because you said you only want direct children.
    # omit recursive=False if you want all nomination tags within each race.
    for nomination in race.find_all('nomination', recursive=False):
        nomination['raceid'] = raceid
print(soup.prettify("latin-1"))
d = pq(html)
for race_el in d('race'):
    race = pq(race_el)
    race_id = race.attr('id')

    # get the nominations and add the attribute

    for nom_el in race.items('nomination'):
        pq(nom_el).attr('raceid', race_id)