Как найти конкретный элемент в анализируемом xml?

#python #xml #xml-parsing #elementtree

Вопрос:

Я новичок в xml xml.etree.ElementTree библиотеке Python и в ней. Я пытаюсь извлечь «Item_desc» и «current_price» из данных Xml ниже в элементе «Элементы». Для анализа XML я следовал этому сообщению.Ниже приведен код, возвращающий данные для «Текущего объема», а также «»Текущее значение/изменение выреза». Не уверен, что не так с приведенным ниже кодом, любая помощь будет признательна.

Заранее спасибо за ваше время и усилия.

XML-данные

 b'<?xml version='1.0' encoding='UTF-8'?><results exportTime="2021-10-03 14:36:22 CDT"><report label="National Daily Cutter Cow Cutout and Boxed Cow Beef Cuts - Negotiated - Afternoon" slug="LM_XB405"><record report_date="09/24/2021" narrative="null"><report label="Current Cutout Value/Change"><record current_cutout_value="232.67" change_cutout_value="-.03"/></report><report label="Items"><record item_desc="90% lean  " current_price="276.93" current_value="154.64" change_value=".00"/><record item_desc="100% lean inside round  " current_price="563.93" current_value="13.08" change_value=".09"/><record item_desc="100% lean, flats and eyes  " current_price="429.52" current_value="9.96" change_value=".00"/><record item_desc="100% lean, S.P.B.  " current_price="431.54" current_value="21.58" change_value=".00"/><record item_desc="Chuck Tender  " current_price="311.27" current_value="3.11" change_value="-.02"/><record item_desc="Knuckle  4-7 lbs." current_price="323.60" current_value="8.19" change_value=".01"/><record item_desc="Tenderloin  2-3 lbs." current_price="442.55" current_value="2.35" change_value="-.06"/><record item_desc="Tenderloin  3-4 lbs." current_price="663.86" current_value="4.91" change_value=".00"/><record item_desc="Ribeye Roll  4-6 lbs." current_price="405.00" current_value="4.25" change_value=".00"/><record item_desc="Ribeye Roll  6-8 lbs." current_price="392.05" current_value="2.90" change_value="-.06"/><record item_desc="Ribeye Roll  8up lbs." current_price="435.00" current_value="3.18" change_value=".00"/><record item_desc="Flank Steak  " current_price="367.34" current_value="1.54" change_value=".01"/><record item_desc="Kidney, Edible  " current_price="40.00" current_value=".18" change_value=".00"/><record item_desc="Fat, inedible  " current_price="44.72" current_value="1.04" change_value=".00"/><record item_desc="Bone  " current_price="7.32" current_value="1.76" change_value=".00"/></report><report label="Current Volume"><record boner_volume_loads="17.31" cutter_volume_loads="4.11" bbcc_volume_loads="19.47" lean_volume_loads="19.09" frozen_volume_loads="4.61" boner_volume_pounds="692,580" cutter_volume_pounds="164,565" bbcc_volume_pounds="778,700" lean_volume_pounds="763,409" frozen_volume_pounds="184,527"/></report><report label="BONER/BREAKER"><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="11" total_pounds="67,507" weighted_avg="496.91" change_in_wtd_avg="4.35"/><record item_desc="Rib, ribeye roll, 8-10 lbs. (112)" number_trades="32" total_pounds="45,014" weighted_avg="563.10" change_in_wtd_avg="-8.29"/><record item_desc="Rib, ribeye roll, 10-up lbs. (112)" number_trades="52" total_pounds="110,549" weighted_avg="523.10" change_in_wtd_avg="-6.89"/><record item_desc="Rib, ribeye roll-lip-on, 8-dn lbs. (112A)" number_trades="9" total_pounds="14,619" weighted_avg="745.28" change_in_wtd_avg=".72"/><record item_desc="Rib, ribeye roll-lip-on, 8-up lbs. (112A)" number_trades="18" total_pounds="23,518" weighted_avg="590.82" change_in_wtd_avg="-8.21"/><record item_desc="Chuck, boneless 85% ( )" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Chuck, brisket (120)" number_trades="13" total_pounds="21,366" weighted_avg="320.60" change_in_wtd_avg="-.72"/><record item_desc="Round, top inside, 10-dn lbs. (168)" number_trades="13" total_pounds="43,841" weighted_avg="288.11" change_in_wtd_avg="-3.57"/><record item_desc="Round, top inside, 10-up lbs. (168)" number_trades="5" total_pounds="4,188" weighted_avg="378.20" change_in_wtd_avg=".00"/><record item_desc="Round, top inside c-off, 8-10 lbs. (169A)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 10-14 lbs. (169A)" number_trades="14" total_pounds="160,462" weighted_avg="426.16" change_in_wtd_avg=".00"/><record item_desc="Round, top inside c-off, 14-up lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, outside round (171B)" number_trades="6" total_pounds="22,900" weighted_avg="432.18" change_in_wtd_avg=".00"/><record item_desc="Round, eye of round (171C)" number_trades="37" total_pounds="69,061" weighted_avg="418.83" change_in_wtd_avg="1.02"/><record item_desc="Loin, Semi-Bnls Short Loin, 13-dn lbs. ( )" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, Semi-Bnls Short Loin, 13-up lbs. ( )" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, strip, bnls, 7-9 lbs. (180)" number_trades="5" total_pounds="3,232" weighted_avg="337.92" change_in_wtd_avg=".53"/><record item_desc="Loin, strip, bnls, 9-up lbs. (180)" number_trades="28" total_pounds="36,542" weighted_avg="364.57" change_in_wtd_avg="-8.85"/><record item_desc="Loin, sirloin butt (182)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, top sirloin butt (184)" number_trades="17" total_pounds="29,315" weighted_avg="316.51" change_in_wtd_avg=".57"/><record item_desc="Loin, bottom sirloin butt flap, bnls. (185A)" number_trades="13" total_pounds="36,343" weighted_avg="376.82" change_in_wtd_avg="9.17"/><record item_desc="Loin, butt tender, peeled (191A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="CUTTER/CANNER"><record item_desc="Rib, ribeye roll, 4-6 lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="42" total_pounds="164,565" weighted_avg="389.13" change_in_wtd_avg="-11.84"/><record item_desc="Rib, ribeye roll, 8-up lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="100% LEAN"><record item_desc="Inside round - Combo" number_trades="16" total_pounds="101,110" weighted_avg="561.59" change_in_wtd_avg="1.95"/><record item_desc="Inside round - Boxed" number_trades="27" total_pounds="40,350" weighted_avg="569.80" change_in_wtd_avg="8.22"/><record item_desc="Outside round" number_trades="4" total_pounds="33,558" weighted_avg="429.74" change_in_wtd_avg="null"/><record item_desc="Eye of round" number_trades="19" total_pounds="30,408" weighted_avg="435.41" change_in_wtd_avg="-.74"/><record item_desc="Flats and eyes - Combo" number_trades="14" total_pounds="206,885" weighted_avg="428.61" change_in_wtd_avg="-.30"/><record item_desc="Flats and eyes - Boxed" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Striploin" number_trades="81" total_pounds="243,034" weighted_avg="466.56" change_in_wtd_avg="-1.73"/><record item_desc="S.P.B. - Combo" number_trades="12" total_pounds="108,064" weighted_avg="431.54" change_in_wtd_avg="-.06"/><record item_desc="S.P.B. - Boxed" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="B/B and C/C"><record item_desc="Chuck, chuck tender (116B)" number_trades="30" total_pounds="73,521" weighted_avg="311.27" change_in_wtd_avg="-2.08"/><record item_desc="Round, knuckle, peeled (167A)" number_trades="39" total_pounds="199,293" weighted_avg="323.60" change_in_wtd_avg=".28"/><record item_desc="Loin, tenderloin, 2-3 lbs. (190)" number_trades="6" total_pounds="8,983" weighted_avg="447.16" change_in_wtd_avg="-12.52"/><record item_desc="Loin, tenderloin, 3-4 lbs. (190)" number_trades="43" total_pounds="69,979" weighted_avg="663.86" change_in_wtd_avg=".20"/><record item_desc="Loin, tenderloin, 4-5 lbs. (190)" number_trades="169" total_pounds="212,729" weighted_avg="773.68" change_in_wtd_avg="-4.71"/><record item_desc="Loin, tenderloin, 5-up lbs. (190)" number_trades="37" total_pounds="43,056" weighted_avg="617.55" change_in_wtd_avg="13.85"/><record item_desc="Flank, flank steak (193)" number_trades="82" total_pounds="116,533" weighted_avg="390.93" change_in_wtd_avg="1.18"/><record item_desc="Flank, rough ()" number_trades="44" total_pounds="54,606" weighted_avg="322.56" change_in_wtd_avg="-5.70"/></report><report label="FROZEN BONER/BREAKER"><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll, 8-10 lbs. (112)" number_trades="6" total_pounds="16,005" weighted_avg="473.41" change_in_wtd_avg=".00"/><record item_desc="Rib, ribeye roll, 10-up lbs. (112)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll-lip-on, 8-dn lbs. (112A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll-lip-on, 8-up lbs. (112A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 8-10 lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 10-14 lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 14-up lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, strip, bnls, 7-9 lbs. (180)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, strip, bnls, 9-up lbs. (180)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="FROZEN CUTTER/CANNER"><record item_desc="Rib, ribeye roll, 4-6 lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="5" total_pounds="85,800" weighted_avg="397.65" change_in_wtd_avg="-2.26"/><record item_desc="Rib, ribeye roll, 8-up lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="FROZEN B/B and C/C"><record item_desc="Loin, tenderloin, 2-3 lbs. (190)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Loin, tenderloin, 3-4 lbs. (190)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, tenderloin, 4-5 lbs. (190)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Loin, tenderloin, 5-up lbs. (190)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Flank, flank steak (193)" number_trades="10" total_pounds="77,922" weighted_avg="332.06" change_in_wtd_avg="-.32"/></report></record></report></results>'
 

Текущий Код:

 for child in root1.iter('record'):
    print(child.attrib.get('item_desc'))
 

Комментарии:

1. Проверьте XML. Начинается с <results> элемента и заканчивается <report> . Несоответствие элементов приведет к ошибке синтаксического анализа.

2. Начните с загрузки КОРРЕКТНОГО , хорошо отформатированного XML-документа. Текущий вариант недействителен.

3. Привет, Biggboss2019, я ответил на ваш вопрос. Пожалуйста, взгляните на это.

4. @балдерман… Обновлен XML

Ответ №1:

Во-первых, то, xml что вы упомянули, неверно, я это исправил:

 b'<?xml version='1.0' encoding='UTF-8'?><results exportTime="2021-10-03 09:12:32 CDT"><report label="National Daily Cutter Cow Cutout and Boxed Cow Beef Cuts - Negotiated - Afternoon" slug="LM_XB405"><record report_date="09/24/2021" narrative="null"/></report><report label="Current Cutout Value/Change"><record current_cutout_value="232.67" change_cutout_value="-.03"/></report><report label="Items"><record item_desc="90% lean  " current_price="276.93" current_value="154.64" change_value=".00"/><record item_desc="100% lean inside round  " current_price="563.93" current_value="13.08" change_value=".09"/><record item_desc="100% lean, flats and eyes  " current_price="429.52" current_value="9.96" change_value=".00"/><record item_desc="100% lean, S.P.B.  " current_price="431.54" current_value="21.58" change_value=".00"/><record item_desc="Chuck Tender  " current_price="311.27" current_value="3.11" change_value="-.02"/><record item_desc="Knuckle  4-7 lbs." current_price="323.60" current_value="8.19" change_value=".01"/><record item_desc="Tenderloin  2-3 lbs." current_price="442.55" current_value="2.35" change_value="-.06"/><record item_desc="Tenderloin  3-4 lbs." current_price="663.86" current_value="4.91" change_value=".00"/><record item_desc="Ribeye Roll  4-6 lbs." current_price="405.00" current_value="4.25" change_value=".00"/><record item_desc="Ribeye Roll  6-8 lbs." current_price="392.05" current_value="2.90" change_value="-.06"/><record item_desc="Ribeye Roll  8up lbs." current_price="435.00" current_value="3.18" change_value=".00"/><record item_desc="Flank Steak  " current_price="367.34" current_value="1.54" change_value=".01"/><record item_desc="Kidney, Edible  " current_price="40.00" current_value=".18" change_value=".00"/><record item_desc="Fat, inedible  " current_price="44.72" current_value="1.04" change_value=".00"/><record item_desc="Bone  " current_price="7.32" current_value="1.76" change_value=".00"/></report><report label="Current Volume"><record boner_volume_loads="17.31" cutter_volume_loads="4.11" bbcc_volume_loads="19.47" lean_volume_loads="19.09" frozen_volume_loads="4.61" boner_volume_pounds="692,580" cutter_volume_pounds="164,565" bbcc_volume_pounds="778,700" lean_volume_pounds="763,409" frozen_volume_pounds="184,527"/></report></results>'  
 

Для того, чтобы достичь того, чего вы ожидаете, просто повторите children root label то, чему равен его атрибут "Items" .

 import xml.etree.ElementTree as et
root1 = et.fromstring(b'<?xml version='1.0' encoding='UTF-8'?><results exportTime="2021-10-03 09:12:32 CDT"><report label="National Daily Cutter Cow Cutout and Boxed Cow Beef Cuts - Negotiated - Afternoon" slug="LM_XB405"><record report_date="09/24/2021" narrative="null"/></report><report label="Current Cutout Value/Change"><record current_cutout_value="232.67" change_cutout_value="-.03"/></report><report label="Items"><record item_desc="90% lean  " current_price="276.93" current_value="154.64" change_value=".00"/><record item_desc="100% lean inside round  " current_price="563.93" current_value="13.08" change_value=".09"/><record item_desc="100% lean, flats and eyes  " current_price="429.52" current_value="9.96" change_value=".00"/><record item_desc="100% lean, S.P.B.  " current_price="431.54" current_value="21.58" change_value=".00"/><record item_desc="Chuck Tender  " current_price="311.27" current_value="3.11" change_value="-.02"/><record item_desc="Knuckle  4-7 lbs." current_price="323.60" current_value="8.19" change_value=".01"/><record item_desc="Tenderloin  2-3 lbs." current_price="442.55" current_value="2.35" change_value="-.06"/><record item_desc="Tenderloin  3-4 lbs." current_price="663.86" current_value="4.91" change_value=".00"/><record item_desc="Ribeye Roll  4-6 lbs." current_price="405.00" current_value="4.25" change_value=".00"/><record item_desc="Ribeye Roll  6-8 lbs." current_price="392.05" current_value="2.90" change_value="-.06"/><record item_desc="Ribeye Roll  8up lbs." current_price="435.00" current_value="3.18" change_value=".00"/><record item_desc="Flank Steak  " current_price="367.34" current_value="1.54" change_value=".01"/><record item_desc="Kidney, Edible  " current_price="40.00" current_value=".18" change_value=".00"/><record item_desc="Fat, inedible  " current_price="44.72" current_value="1.04" change_value=".00"/><record item_desc="Bone  " current_price="7.32" current_value="1.76" change_value=".00"/></report><report label="Current Volume"><record boner_volume_loads="17.31" cutter_volume_loads="4.11" bbcc_volume_loads="19.47" lean_volume_loads="19.09" frozen_volume_loads="4.61" boner_volume_pounds="692,580" cutter_volume_pounds="164,565" bbcc_volume_pounds="778,700" lean_volume_pounds="763,409" frozen_volume_pounds="184,527"/></report></results>')
for child in root1 :
    if child.attrib['label'] != "Items":
        continue
    for record in child.iter('record'):
        print(record.attrib.get('item_desc'))
 

В результате будет:

 90% lean  
100% lean inside round     
100% lean, flats and eyes  
100% lean, S.P.B.
Chuck Tender
Knuckle  4-7 lbs.
Tenderloin  2-3 lbs.       
Tenderloin  3-4 lbs.       
Ribeye Roll  4-6 lbs.      
Ribeye Roll  6-8 lbs.      
Ribeye Roll  8up lbs.      
Flank Steak
Kidney, Edible
Fat, inedible
Bone
 

Комментарии:

1. Спасибо, что ответили на мой вопрос. XML-файл находится здесь — >> mpr.datamart.ams.usda.gov/ws/report/v1/xb/. … Когда я попытался запустить приведенный выше код..код работает нормально,но он не отображает никаких выходных данных. Не знаете, в чем проблема ?

2. Это сработало для меня, и я тоже показал результат. @biggboss2019

3. Воспользуйся моим Xml , может быть, причина в этом.

4. Обновлен xml-код в разделе xml-данные

5. У тебя xml есть некоторые проблемы… Я только что проверил это. пожалуйста, используйте мой xml , который я вставил в свой ответ.

Ответ №2:

Что-то не так с форматом вашего XML-файла. Следующий код должен работать, если ваш файл правильно отформатирован.

Сначала мы загружаем XML-дерево:

 import xml.etree.ElementTree as ET
tree = ET.fromstring(b'<?xml version='1.0' encoding='UTF-8'?><results exportTime="2021-10-03 14:36:22 CDT"><report label="National Daily Cutter Cow Cutout and Boxed Cow Beef Cuts - Negotiated - Afternoon" slug="LM_XB405"><record report_date="09/24/2021" narrative="null"><report label="Current Cutout Value/Change"><record current_cutout_value="232.67" change_cutout_value="-.03"/></report><report label="Items"><record item_desc="90% lean  " current_price="276.93" current_value="154.64" change_value=".00"/><record item_desc="100% lean inside round  " current_price="563.93" current_value="13.08" change_value=".09"/><record item_desc="100% lean, flats and eyes  " current_price="429.52" current_value="9.96" change_value=".00"/><record item_desc="100% lean, S.P.B.  " current_price="431.54" current_value="21.58" change_value=".00"/><record item_desc="Chuck Tender  " current_price="311.27" current_value="3.11" change_value="-.02"/><record item_desc="Knuckle  4-7 lbs." current_price="323.60" current_value="8.19" change_value=".01"/><record item_desc="Tenderloin  2-3 lbs." current_price="442.55" current_value="2.35" change_value="-.06"/><record item_desc="Tenderloin  3-4 lbs." current_price="663.86" current_value="4.91" change_value=".00"/><record item_desc="Ribeye Roll  4-6 lbs." current_price="405.00" current_value="4.25" change_value=".00"/><record item_desc="Ribeye Roll  6-8 lbs." current_price="392.05" current_value="2.90" change_value="-.06"/><record item_desc="Ribeye Roll  8up lbs." current_price="435.00" current_value="3.18" change_value=".00"/><record item_desc="Flank Steak  " current_price="367.34" current_value="1.54" change_value=".01"/><record item_desc="Kidney, Edible  " current_price="40.00" current_value=".18" change_value=".00"/><record item_desc="Fat, inedible  " current_price="44.72" current_value="1.04" change_value=".00"/><record item_desc="Bone  " current_price="7.32" current_value="1.76" change_value=".00"/></report><report label="Current Volume"><record boner_volume_loads="17.31" cutter_volume_loads="4.11" bbcc_volume_loads="19.47" lean_volume_loads="19.09" frozen_volume_loads="4.61" boner_volume_pounds="692,580" cutter_volume_pounds="164,565" bbcc_volume_pounds="778,700" lean_volume_pounds="763,409" frozen_volume_pounds="184,527"/></report><report label="BONER/BREAKER"><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="11" total_pounds="67,507" weighted_avg="496.91" change_in_wtd_avg="4.35"/><record item_desc="Rib, ribeye roll, 8-10 lbs. (112)" number_trades="32" total_pounds="45,014" weighted_avg="563.10" change_in_wtd_avg="-8.29"/><record item_desc="Rib, ribeye roll, 10-up lbs. (112)" number_trades="52" total_pounds="110,549" weighted_avg="523.10" change_in_wtd_avg="-6.89"/><record item_desc="Rib, ribeye roll-lip-on, 8-dn lbs. (112A)" number_trades="9" total_pounds="14,619" weighted_avg="745.28" change_in_wtd_avg=".72"/><record item_desc="Rib, ribeye roll-lip-on, 8-up lbs. (112A)" number_trades="18" total_pounds="23,518" weighted_avg="590.82" change_in_wtd_avg="-8.21"/><record item_desc="Chuck, boneless 85% ( )" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Chuck, brisket (120)" number_trades="13" total_pounds="21,366" weighted_avg="320.60" change_in_wtd_avg="-.72"/><record item_desc="Round, top inside, 10-dn lbs. (168)" number_trades="13" total_pounds="43,841" weighted_avg="288.11" change_in_wtd_avg="-3.57"/><record item_desc="Round, top inside, 10-up lbs. (168)" number_trades="5" total_pounds="4,188" weighted_avg="378.20" change_in_wtd_avg=".00"/><record item_desc="Round, top inside c-off, 8-10 lbs. (169A)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 10-14 lbs. (169A)" number_trades="14" total_pounds="160,462" weighted_avg="426.16" change_in_wtd_avg=".00"/><record item_desc="Round, top inside c-off, 14-up lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, outside round (171B)" number_trades="6" total_pounds="22,900" weighted_avg="432.18" change_in_wtd_avg=".00"/><record item_desc="Round, eye of round (171C)" number_trades="37" total_pounds="69,061" weighted_avg="418.83" change_in_wtd_avg="1.02"/><record item_desc="Loin, Semi-Bnls Short Loin, 13-dn lbs. ( )" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, Semi-Bnls Short Loin, 13-up lbs. ( )" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, strip, bnls, 7-9 lbs. (180)" number_trades="5" total_pounds="3,232" weighted_avg="337.92" change_in_wtd_avg=".53"/><record item_desc="Loin, strip, bnls, 9-up lbs. (180)" number_trades="28" total_pounds="36,542" weighted_avg="364.57" change_in_wtd_avg="-8.85"/><record item_desc="Loin, sirloin butt (182)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, top sirloin butt (184)" number_trades="17" total_pounds="29,315" weighted_avg="316.51" change_in_wtd_avg=".57"/><record item_desc="Loin, bottom sirloin butt flap, bnls. (185A)" number_trades="13" total_pounds="36,343" weighted_avg="376.82" change_in_wtd_avg="9.17"/><record item_desc="Loin, butt tender, peeled (191A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="CUTTER/CANNER"><record item_desc="Rib, ribeye roll, 4-6 lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="42" total_pounds="164,565" weighted_avg="389.13" change_in_wtd_avg="-11.84"/><record item_desc="Rib, ribeye roll, 8-up lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="100% LEAN"><record item_desc="Inside round - Combo" number_trades="16" total_pounds="101,110" weighted_avg="561.59" change_in_wtd_avg="1.95"/><record item_desc="Inside round - Boxed" number_trades="27" total_pounds="40,350" weighted_avg="569.80" change_in_wtd_avg="8.22"/><record item_desc="Outside round" number_trades="4" total_pounds="33,558" weighted_avg="429.74" change_in_wtd_avg="null"/><record item_desc="Eye of round" number_trades="19" total_pounds="30,408" weighted_avg="435.41" change_in_wtd_avg="-.74"/><record item_desc="Flats and eyes - Combo" number_trades="14" total_pounds="206,885" weighted_avg="428.61" change_in_wtd_avg="-.30"/><record item_desc="Flats and eyes - Boxed" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Striploin" number_trades="81" total_pounds="243,034" weighted_avg="466.56" change_in_wtd_avg="-1.73"/><record item_desc="S.P.B. - Combo" number_trades="12" total_pounds="108,064" weighted_avg="431.54" change_in_wtd_avg="-.06"/><record item_desc="S.P.B. - Boxed" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="B/B and C/C"><record item_desc="Chuck, chuck tender (116B)" number_trades="30" total_pounds="73,521" weighted_avg="311.27" change_in_wtd_avg="-2.08"/><record item_desc="Round, knuckle, peeled (167A)" number_trades="39" total_pounds="199,293" weighted_avg="323.60" change_in_wtd_avg=".28"/><record item_desc="Loin, tenderloin, 2-3 lbs. (190)" number_trades="6" total_pounds="8,983" weighted_avg="447.16" change_in_wtd_avg="-12.52"/><record item_desc="Loin, tenderloin, 3-4 lbs. (190)" number_trades="43" total_pounds="69,979" weighted_avg="663.86" change_in_wtd_avg=".20"/><record item_desc="Loin, tenderloin, 4-5 lbs. (190)" number_trades="169" total_pounds="212,729" weighted_avg="773.68" change_in_wtd_avg="-4.71"/><record item_desc="Loin, tenderloin, 5-up lbs. (190)" number_trades="37" total_pounds="43,056" weighted_avg="617.55" change_in_wtd_avg="13.85"/><record item_desc="Flank, flank steak (193)" number_trades="82" total_pounds="116,533" weighted_avg="390.93" change_in_wtd_avg="1.18"/><record item_desc="Flank, rough ()" number_trades="44" total_pounds="54,606" weighted_avg="322.56" change_in_wtd_avg="-5.70"/></report><report label="FROZEN BONER/BREAKER"><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll, 8-10 lbs. (112)" number_trades="6" total_pounds="16,005" weighted_avg="473.41" change_in_wtd_avg=".00"/><record item_desc="Rib, ribeye roll, 10-up lbs. (112)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll-lip-on, 8-dn lbs. (112A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll-lip-on, 8-up lbs. (112A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 8-10 lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 10-14 lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Round, top inside c-off, 14-up lbs. (169A)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, strip, bnls, 7-9 lbs. (180)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, strip, bnls, 9-up lbs. (180)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="FROZEN CUTTER/CANNER"><record item_desc="Rib, ribeye roll, 4-6 lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Rib, ribeye roll, 6-8 lbs. (112)" number_trades="5" total_pounds="85,800" weighted_avg="397.65" change_in_wtd_avg="-2.26"/><record item_desc="Rib, ribeye roll, 8-up lbs. (112)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/></report><report label="FROZEN B/B and C/C"><record item_desc="Loin, tenderloin, 2-3 lbs. (190)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Loin, tenderloin, 3-4 lbs. (190)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Loin, tenderloin, 4-5 lbs. (190)" number_trades="null" total_pounds="null" weighted_avg="null" change_in_wtd_avg="null"/><record item_desc="Loin, tenderloin, 5-up lbs. (190)" number_trades="0" total_pounds="0" weighted_avg=".00" change_in_wtd_avg="null"/><record item_desc="Flank, flank steak (193)" number_trades="10" total_pounds="77,922" weighted_avg="332.06" change_in_wtd_avg="-.32"/></report></record></report></results>')
 

Найдите узел элементы:

 item = tree.find(".//report[@label='Items']")
 

Делайте что угодно с записями в элементе:

 for r in item:
    print(r.attrib["item_desc"].ljust(30), r.attrib["current_price"])

90% lean                       276.93
100% lean inside round         563.93
100% lean, flats and eyes      429.52
100% lean, S.P.B.              431.54
Chuck Tender                   311.27
Knuckle  4-7 lbs.              323.60
Tenderloin  2-3 lbs.           442.55
Tenderloin  3-4 lbs.           663.86
Ribeye Roll  4-6 lbs.          405.00
Ribeye Roll  6-8 lbs.          392.05
Ribeye Roll  8up lbs.          435.00
Flank Steak                    367.34
Kidney, Edible                 40.00
Fat, inedible                  44.72
Bone                           7.32
 

Редактировать: если вам нужно получить все «записи» из определенных «отчетов», я бы предложил:

 recs = []
for rep in ["'Items'", "'100% LEAN'"]:
    recs  = tree.findall(f".//*[@label={rep}]/record")
 

где recs сейчас находится список записей.

Комментарии:

1. Спасибо! Когда я попытался выполнить синтаксический анализ, я получил ошибку типа «ожидаемый str, байт или ОС. Объект, подобный пути, а не ответ». XML, который я пытаюсь проанализировать, можно найти здесь ->> mpr.datamart.ams.usda.gov/ws/report/v1/xb/…

2. Да, просто отредактировал мой ответ, чтобы работать с вашей фиксированной XML-строкой nox

3. Спасибо! Что делать, если у нас есть несколько тегов для извлечения, давайте в приведенной выше xml-ссылке.. Я также хотел бы извлечь данные, связанные с тегом «100% бережливый»?

4. Поскольку»Предметы» и»100% ХУДОЙ» кажутся совершенно разными, я бы обрабатывал их отдельно: records_items = tree.findall ( «.//*[@label= «Предметы»]/запись») и records_lean = tree.findall ( » .//*[@label=»100% ХУДОЙ»]/запись»). Если вам нужны похожие записи из разных отчетов, я бы выбрал цикл for или то, что я отредактировал в своем ответе.