Мы в Telegram
Добавить новость

Новости сегодня на DirectAdvert

Новости сегодня от Adwile

Решить задачу на Python (парсинг XML)

Common Requirements

  • Code must correspond to pep8 (use pycodestyle utility for self-check).
    • You can set line lengths up to 120 symbols.

Task Description

For this task, you can join with an RSS reader using Python 3.10.

For the testing, you are going to isolate the parts you will work on. Namely, you are going to work only on the RSS (XML) scrapping part. Your task is to parse the RSS document and provide two formatted outputs: JSON and the standard output.

You are going to:

  • Command line parsing.
  • Receive the XML document from the web.
Because you can create your own style of formatting, it will be difficult to test you. So, we will provide you with the exact style for the format to ease the testing part.

The format of the RSS feed that you are going to parse is RSS 2.0. You can follow the link to get a full understanding of the specification. But in this task, we are asking for the following requirements:

<channel>...</channel> <!-- Required tags are <title>, <link>, <description>  but we are asking you to be able to parse <title>, <link>, <description>, <category>, <language>, <lastBuildDate>, <managingEditor>, <pubDate>, <item> -->
<item>...</item> <!-- All of the fields here are optional, but each item should have at least <title> or <description>, but for the purposes of the test we are asking to be able to parse <title>, <author>, <pubDate>, <link>, <category>, <description> -->
The order of the RSS items in all the output types should be the following:

  • For <channel> element:
    1. <title>
    2. <link>
    3. <lastBuildDate>
    4. <pubDate>
    5. <language>
    6. <category> for category in categories
    7. <managinEditor>
    8. <description>
    9. <item> for item in items
  • For <item> element:
    1. <title>
    2. <author>
    3. <pubDate>
    4. <link>
    5. <category>
    6. <description>
The CLI is going to have the following interface. You can use it for testing purposes when you develop XML document parsing.

usage: rss_reader.py [-h] [--json] [--limit LIMIT]
                    source

Pure Python command-line RSS reader.

positional arguments:
 source         RSS URL

optional arguments:
 -h, --help     show this help message and exit
 --json         Print result as JSON in stdout
 --limit LIMIT  Limit news topics if this parameter is provided

Command Line Arguments

  1. If the limit is not specified, then the user should get all available feeds.
  2. If the limit is larger than the feed size, then the user should get all available news.
  3. The limit argument should also affect JSON generation
  4. In the case of using the --json argument, your utility should convert the news into the JSON format.

Console Output:

  • For <channel> element:
    1. <title> is equal to Feed
    2. <link> is equal to Link
    3. <lastBuildDate> is equal to Last Build Date
    4. <pubDate> is equal to Date
    5. <language> is equal to Language
    6. <category> for category in categories is equal to Categories: category1, category2
    7. <managinEditor> is equal to Editor
    8. <description> is equal to Description
    9. <item> for item in items each item is separated by a custom separator, and all items within except for the description are stuck together.
  • For <item> element:
    1. <title> is equal to Title
    2. <author> is equal to Author
    3. <pubDate> is equal to Date
    4. <link> is equal to Link
    5. <category> is equal to Categories: category1, category2
    6. <description> is on a separate line without any name.
For the console output you are looking for the order of things – channel items go first and then the other items. You should also have a space between the channel elements and items. Also, the description within the item should be on the new line, separated by space. For example:

Feed: Yahoo News - Latest News & Headlines
Link: https://news.yahoo.com/rss
Description: Yahoo news description

Title: Nestor heads into Georgia after tornados damage Florida
Date: Sun, 20 Oct 2019 04:21:44 +0300
Link: https://news.yahoo.com/wet-weekend-tropical-storm-warnings-131131925.html

Nestor raced across Georgia as a post-tropical cyclone late Saturday, hours after the former tropical storm spawned a tornado that damaged homes and a school in central Florida while sparing areas of the Florida Panhandle devastated one year earlier by Hurricane Michael. The storm made landfall Saturday on St. Vincent Island, a nature preserve off Florida's northern Gulf Coast in a lightly populated area of the state, the National Hurricane Center said. Nestor was expected to bring 1 to 3 inches of rain to drought-stricken inland areas on its march across a swath of the U.S. Southeast... <--- !!! THIS IS DESCRIPTION !!!

Title: Some Other Title
Date: Sun, 20 Oct 2019 04:21:44 +0300
Link: https://some.other.link/some-other-news


Some other new cool information. <--- !!! THIS IS DESCRIPTION

JSON Output:

For the JSON output, you are looking for the exact names of the tags. Ask for the pretty output:

{
  "title": "Yahoo News - Latest News & Headlines",
  "link": "https://news.yahoo.com/rss",
  "description": "Yahoo news description",
  "items": [
    {
      "title": "Nestor heads into Georgia after tornados damage Florida",
      "pubDate": "Sun, 20 Oct 2019 04:21:44 +0300",
      "link": "https://some.other.link/some-other-news",
      "description": "Nestor raced across Georgia as a post-tropical cyclone late Saturday, hours after the former tropical storm spawned a tornado that damaged homes and a school in central Florida while sparing areas of the Florida Panhandle devastated one year earlier by Hurricane Michael. The storm made landfall Saturday on St. Vincent Island, a nature preserve off Florida's northern Gulf Coast in a lightly populated area of the state, the National Hurricane Center said. Nestor was expected to bring 1 to 3 inches of rain to drought-stricken inland areas on its march across a swath of the U.S. Southeast..."
    },
    {
      "title": "Some other title",
      "pubDate": "Sun, 20 Oct 2019 04:21:44 +0300",
      "link": "https://some.other.link/some-other-news",
      "description": "Some other new cool information."
    }
  ]
}

Читайте на 123ru.net

Другие проекты от 123ru.net



Архангельск

В Архангельске работать в летнюю навигацию будут девять теплоходов



Жизнь

Российская империя в фото 40




Українські новини

Депутат Миколаївської облради Кормишкін вперше опублікував своє весільне фото



Новости 24 часа

Культура России: как прошёл конкурс бурятского языка для детей в Бурятии?



Game News

Гайд по фарму золота в Solo Leveling: Arise



Москва

Героическое участие армян в СВО. Часть третья



News Every Day

Online Alarm Clock for efficient time management



Происшествия

Столичные росгвардейцы оказали помощь пострадавшим в дорожно-транспортном происшествии



Москва

Путин и Рахмон обсудили усилия России и Таджикистана по борьбе с терроризмом



Тимати

После резкого поста о Надежде Стрелец мама Тимати вступила в дискуссию с подписчиками и неожиданно упомянула Ксению Собчак



Москва

В Москве директора школы осудили по делу о заказном убийстве жены депутата



Андрей Рублёв

Рублёв: быстрая победа над Грикспором связана с тем, что хотел быстрее уйти с корта



Москва

Магнитная буря 2 мая может спровоцировать северное сияние в Москве



Россия

6 городов России, где можно увидеть белые ночи кроме Санкт-Петербурга



Симферополь

В Симферополе проведен рейд по бывшим мигрантам



Москва

Производственные площадки АО «Желдорреммаш» в апреле посетило более 4700 школьников и студентов



Москва

Сергей Собянин рассказал о цифровизации системы здравоохранения



Москва

Работники СЛД «Узловая» филиала «Московский» ООО «ЛокоТех-Сервис» приняли участие региональном этапе «Время молодых. Работники»



103news.com — быстрее, чем Я..., самые свежие и актуальные новости Вашего города — каждый день, каждый час с ежеминутным обновлением! Мгновенная публикация на языке оригинала, без модерации и без купюр в разделе Пользователи сайта 103news.com.

Как добавить свои новости в наши трансляции? Очень просто. Достаточно отправить заявку на наш электронный адрес mail@29ru.net с указанием адреса Вашей ленты новостей в формате RSS или подать заявку на включение Вашего сайта в наш каталог через форму. После модерации заявки в течении 24 часов Ваша лента новостей начнёт транслироваться в разделе Вашего города. Все новости в нашей ленте новостей отсортированы поминутно по времени публикации, которое указано напротив каждой новости справа также как и прямая ссылка на источник информации. Если у Вас есть интересные фото Вашего города или других населённых пунктов Вашего региона мы также готовы опубликовать их в разделе Вашего города в нашем каталоге региональных сайтов, который на сегодняшний день является самым большим региональным ресурсом, охватывающим все города не только России и Украины, но ещё и Белоруссии и Абхазии. Прислать фото можно здесь. Оперативно разместить свою новость в Вашем городе можно самостоятельно через форму.

Другие популярные новости дня сегодня


Новости 24/7 Все города России





Топ 10 новостей последнего часа




Новости России

Анатолий Багаев стал лучшим водителем скорой в Подмосковье

Россия и Дети: театр кукол Ульгэр в Бурятии покажет концерт-представление "Вальс Победы"

РЕПОРТАЖ: Время добра и чудес

Магнитная буря 2 мая может спровоцировать северное сияние в Москве


Москва

Продвижение новых песен с высоким результатом






Rss.plus

Продвижение новых песен с высоким результатом

6 городов России, где можно увидеть белые ночи кроме Санкт-Петербурга

Культура России: как прошёл конкурс бурятского языка для детей в Бурятии?

Героическое участие армян в СВО. Часть третья

Moscow.media
Москва

Собянин: На Пасху городской транспорт будет работать дольше



103news.comмеждународная интерактивная информационная сеть (ежеминутные новости с ежедневным интелектуальным архивом). Только у нас — все главные новости дня без политической цензуры. "103 Новости" — абсолютно все точки зрения, трезвая аналитика, цивилизованные споры и обсуждения без взаимных обвинений и оскорблений. Помните, что не у всех точка зрения совпадает с Вашей. Уважайте мнение других, даже если Вы отстаиваете свой взгляд и свою позицию. 103news.com — облегчённая версия старейшего обозревателя новостей 123ru.net.

Мы не навязываем Вам своё видение, мы даём Вам объективный срез событий дня без цензуры и без купюр. Новости, какие они есть — онлайн (с поминутным архивом по всем городам и регионам России, Украины, Белоруссии и Абхазии).

103news.com — живые новости в прямом эфире!

В любую минуту Вы можете добавить свою новость мгновенно — здесь.

Музыкальные новости

Валерий Гергиев

Собянин поздравил народного артиста России Валерия Гергиева с днём рождения




Спорт в России и мире

Алексей Смирнов – актер, которого, надеюсь, еще не забыли

Полина Гагарина опровергла «уход на пенсию» и рассказала о новом рубеже

В дивизии имени Ф.Э. Дзержинского Росгвардии стартовал турнир по боксу «Кубок Победы»

Полина Гагарина: «Нет, я не ухожу на пенсию»


Даниил Медведев

Медведев обыграл Бублика и вышел в четвертьфинал "Мастерса" в Мадриде



Новости Крыма на Sevpoisk.ru


Россия

Третья по силе магнитная буря за 2024 год началась в России



Частные объявления в Вашем городе, в Вашем регионе и в России