Advertisement
JmihPodvalbniy

Untitled

May 21st, 2024
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.41 KB | Software | 0 0
  1. #1) Скачать XML файл https://drive.google.com/file/d/1_TNSX3RAzlhUx-CabYZznyQrwnsGsoGL/view?usp=sharing
  2. #1.1) Спарсить все категории товаров и сохранить в отдельный текстовый файл
  3. import xml.etree.ElementTree as ET
  4.  
  5. file_path = "C:/Users/TRAVK/Downloads/lite_yafbs_prices.ext.xml"
  6. #Укажите свой путь к файлу
  7. tree = ET.parse(file_path)
  8. root = tree.getroot()
  9.  
  10. with open("categories.txt", "w", encoding='utf-8') as f:
  11.  
  12.     for category in root.iter('category'):
  13.         f.write(category.text + "\n")
  14. #1.2) Спарсить всю информацию о товарах offers (все вложенные теги и атрибуты) и сохранить в отдельный текстовый файл
  15. import xml.etree.ElementTree as ET
  16.  
  17. file_path = "C:/Users/TRAVK/Downloads/lite_yafbs_prices.ext.xml"
  18. #Укажите свой путь к файлу
  19. tree = ET.parse(file_path)
  20. root = tree.getroot()
  21.  
  22. with open("offers_info.txt", "w", encoding='utf-8') as f:
  23.  
  24.     for offer in root.iter('offer'):
  25.  
  26.         f.write(f"Offer ID: {offer.attrib['id']}\n")
  27.  
  28.         for child in offer:
  29.             if child.text is not None:
  30.                 f.write(f"{child.tag}: {child.text}\n")
  31.             else:
  32.                 f.write(f"{child.tag}: \n")
  33.  
  34.             for key, value in child.attrib.items():
  35.                 f.write(f"  - {key}: {value}\n")
  36.  
  37.         f.write("\n")
  38.  
  39.  
  40. #2) Скачать JSON файл https://drive.google.com/file/d/1kLJJLlCbRgZy23lRauFDsIkgDUQts4cm/view?usp=sharing
  41. #Спарсить всю информацию о первых 100 товарах и сохранить её в отдельный текстовый файл
  42. with open('data.json', 'r', encoding='utf-8') as f:
  43.     data = f.readlines()
  44.  
  45. products = []
  46. count = 0
  47. for product_str in data:
  48.     if count < 1000:
  49.         product_data = {}
  50.         for item in product_str.strip().split(','):
  51.             if ':' in item:
  52.                 key, value = item.split(':', 1)
  53.                 key = key.strip()
  54.                 value = value.strip()
  55.                 product_data[key] = value
  56.         products.append(product_data)
  57.         count += 1
  58.  
  59. with open('products_data.txt', 'w', encoding='utf-8') as f:
  60.     for product in products:
  61.         for key, value in product.items():
  62.             f.write(f"{key}: {value}\n")
  63.         f.write('---\n')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement