diff --git a/Final_Task.md b/Final_Task.md new file mode 100644 index 00000000..2e2e618a --- /dev/null +++ b/Final_Task.md @@ -0,0 +1,195 @@ +# Introduction to Python. Final task. +You are proposed to implement Python RSS-reader using **python 3.9**. + +The task consists of few iterations. Do not start new iteration if the previous one is not implemented yet. + +## Common requirements. +* It is mandatory to use `argparse` module. +* Codebase must be covered with unit tests with at least 50% coverage. It's a mandatory requirement. +* Yor script should **not** require installation of other services such as mysql server, +postgresql and etc. (except Iteration 6). If it does require such programs, +they should be installed automatically by your script, without user doing anything. +* In case of any mistakes utility should print human-readable. +error explanation. Exception tracebacks in stdout are prohibited in final version of application. +* Docstrings are mandatory for all methods, classes, functions and modules. +* Code must correspond to `pep8` (use `pycodestyle` utility for self-check). + * You can set line length up to 120 symbols. +* Commit messages should provide correct and helpful information about changes in commit. Messages like `Fix bug`, +`Tried to make workable`, `Temp commit` and `Finally works` are prohibited. +* All used third-party packages should be written in the `requirements.txt` file and in installation files (`setup.py`, `setup.cfg`, etc.). +* You have to write a file with documentation. Everything must be documented: how to run scripts, how to run tests, how to install the library and etc. + +## [Iteration 1] One-shot command-line RSS reader. +RSS reader should be a command-line utility which receives [RSS](wikipedia.org/wiki/RSS) URL and prints results in human-readable format. + +You are free to choose format of the news console output. The textbox below provides an example of how it can be implemented: + +```shell +$ rss_reader.py "https://news.yahoo.com/rss/" --limit 1 + +Feed: Yahoo News - Latest News & Headlines + +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 + +[image 2: Nestor heads into Georgia after tornados damage Florida][2]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. + + +Links: +[1]: https://news.yahoo.com/wet-weekend-tropical-storm-warnings-131131925.html (link) +[2]: http://l2.yimg.com/uu/api/res/1.2/Liyq2kH4HqlYHaS5BmZWpw--/YXBwaWQ9eXRhY2h5b247aD04Njt3PTEzMDs-/https://media.zenfs.com/en/ap.org/5ecc06358726cabef94585f99050f4f0 (image) + +``` + +Utility should provide the following interface: +```shell +usage: rss_reader.py [-h] [--version] [--json] [--verbose] [--limit LIMIT] + source + +Pure Python command-line RSS reader. + +positional arguments: + source RSS URL + +optional arguments: + -h, --help show this help message and exit + --version Print version info + --json Print result as JSON in stdout + --verbose Outputs verbose status messages + --limit LIMIT Limit news topics if this parameter provided + +``` + +In case of using `--json` argument your utility should convert the news into [JSON](https://en.wikipedia.org/wiki/JSON) format. +You should come up with the JSON structure on you own and describe it in the README.md file for your repository or in a separate documentation file. + + + +With the argument `--verbose` your program should print all logs in stdout. + +### Task clarification (I) + +1) If `--version` option is specified app should _just print its version_ and stop. +2) User should be able to use `--version` option without specifying RSS URL. For example: +``` +> python rss_reader.py --version +"Version 1.4" +``` +3) The version is supposed to change with every iteration. +4) If `--limit` is not specified, then user should get _all_ available feed. +5) If `--limit` is larger than feed size then user should get _all_ available news. +6) `--verbose` should print logs _in the process_ of application running, _not after everything is done_. +7) Make sure that your app **has no encoding issues** (meaning symbols like `'` and etc) when printing news to _stdout_. +8) Make sure that your app **has no encoding issues** (meaning symbols like `'` and etc) when printing news to _stdout in JSON format_. +9) It is preferrable to have different custom exceptions for different situations(If needed). +10) The `--limit` argument should also affect JSON generation. + + +## [Iteration 2] Distribution. + +* Utility should be wrapped into distribution package with `setuptools`. +* This package should export CLI utility named `rss-reader`. + + +### Task clarification (II) + +1) User should be able to run your application _both_ with and without installation of CLI utility, +meaning that this should work: + +``` +> python rss_reader.py ... +``` + +as well as this: + +``` +> rss_reader ... +``` +2) Make sure your second iteration works on a clean machie with python 3.9. (!) +3) Keep in mind that installed CLI utility should have the same functionality, so do not forget to update dependencies and packages. + + +## [Iteration 3] News caching. +The RSS news should be stored in a local storage while reading. The way and format of this storage you can choose yourself. +Please describe it in a separate section of README.md or in the documentation. + +New optional argument `--date` must be added to your utility. It should take a date in `%Y%m%d` format. +For example: `--date 20191020` +Here date means actual *publishing date* not the date when you fetched the news. + +The cashed news can be read with it. The new from the specified day will be printed out. +If the news are not found return an error. + +If the `--date` argument is not provided, the utility should work like in the previous iterations. + +### Task clarification (III) +1) Try to make your application crossplatform, meaning that it should work on both Linux and Windows. +For example when working with filesystem, try to use `os.path` lib instead of manually concatenating file paths. +2) `--date` should **not** require internet connection to fetch news from local cache. +3) User should be able to use `--date` without specifying RSS source. For example: +``` +> python rss_reader.py --date 20191206 +...... +``` +Or for second iteration (when installed using setuptools): +``` +> rss_reader --date 20191206 +...... +``` +4) If `--date` specified _together with RSS source_, then app should get news _for this date_ from local cache that _were fetched from specified source_. +5) `--date` should work correctly with both `--json`, `--limit`, `--verbose` and their different combinations. + +## [Iteration 4] Format converter. + +You should implement the conversion of news in at least two of the suggested format: `.mobi`, `.epub`, `.fb2`, `.html`, `.pdf` + +New optional argument must be added to your utility. This argument receives the path where new file will be saved. The arguments should represents which format will be generated. + +For example: `--to-mobi` or `--to-fb2` or `--to-epub` + +You can choose yourself the way in which the news will be displayed, but the final text result should contain pictures and links, if they exist in the original article and if the format permits to store this type of data. + +### Task clarification (IV) + +Convertation options should work correctly together with all arguments that were implemented in Iterations 1-3. For example: +* Format convertation process should be influenced by `--limit`. +* If `--json` is specified together with convertation options, then JSON news should +be printed to stdout, and converted file should contain news in normal format. +* Logs from `--verbose` should be printed in stdout and not added to the resulting file. +* `--date` should also work correctly with format converter and to not require internet access. + +## * [Iteration 5] Output colorization. +> Note: An optional iteration, it is not necessary to implement it. You can move on with it only if all the previous iterations (from 1 to 4) are completely implemented. + +You should add new optional argument `--colorize`, that will print the result of the utility in colorized mode. + +*If the argument is not provided, the utility should work like in the previous iterations.* + +> Note: Take a look at the [colorize](https://pypi.org/project/colorize/) library + +## * [Iteration 6] Web-server. +> Note: An optional iteration, it is not necessary to implement it. You can move on with it only if all the previous iterations (from 1 to 4) are completely implemented. Introduction to Python course does not cover the topics that are needed for the implementation of this part. + +There are several mandatory requirements in this iteration: +* `Docker` + `docker-compose` usage (at least 2 containers: one for web-application, one for DB) +* Web application should provide all the implemented in the previous parts of the task functionality, using the REST API: + * One-shot conversion from RSS to Human readable format + * Server-side news caching + * Conversion in epub, mobi, fb2 or other formats + +Feel free to choose the way of implementation, libraries and frameworks. (We suggest you `Django Rest Framework` + `PostgreSQL` combination) + +You can implement any functionality that you want. The only requirement is to add the description into README file or update project documentation, for example: +* authorization/authentication +* automatic scheduled news update +* adding new RSS sources using API + +--- +Implementations will be checked with the latest cPython interpreter of 3.9 branch. +--- + +> Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability. **John F. Woods** diff --git a/RULES.md b/RULES.md new file mode 100644 index 00000000..9a72034f --- /dev/null +++ b/RULES.md @@ -0,0 +1,12 @@ +# Final task +Final task (`FT`) for EPAM Python Training 2022.03 + +## Rules +* All work has to be implemented in the `master` branch in forked repository. If you think that `FT` is ready, please open a pull request (`PR`) to our repo. +* When a `PR` will be ready, please mark it with the `final_task` label. +* You have one month to finish `FT`. Commits commited after deadline will be ignored. +* At least the first 4 iterations must be done. +* `FT` you can find in the `Final_Task.md` file. + +### Good luck! + diff --git a/Sholomitski Dmitry/MANIFEST.in b/Sholomitski Dmitry/MANIFEST.in new file mode 100644 index 00000000..3d387c34 --- /dev/null +++ b/Sholomitski Dmitry/MANIFEST.in @@ -0,0 +1,2 @@ +include README.md +include requirements.txt \ No newline at end of file diff --git a/Sholomitski Dmitry/requirements.txt b/Sholomitski Dmitry/requirements.txt new file mode 100644 index 00000000..762b221b --- /dev/null +++ b/Sholomitski Dmitry/requirements.txt @@ -0,0 +1,9 @@ +setuptools~=62.1.0 +requests~=2.27.1 +bs4~=0.0.1 +beautifulsoup4~=4.11.1 +dateparser~=1.1.1 +reportlab~=3.6.10 +xhtml2pdf~=0.2.8 +colorama~=0.4.4 +Pygments~=2.12.0 \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Fonts/__init__.py b/Sholomitski Dmitry/rss_reader/Fonts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/Sholomitski Dmitry/rss_reader/Fonts/calibri.ttf b/Sholomitski Dmitry/rss_reader/Fonts/calibri.ttf new file mode 100644 index 00000000..aac47261 Binary files /dev/null and b/Sholomitski Dmitry/rss_reader/Fonts/calibri.ttf differ diff --git a/Sholomitski Dmitry/rss_reader/README.md b/Sholomitski Dmitry/rss_reader/README.md new file mode 100644 index 00000000..1907209f --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/README.md @@ -0,0 +1,69 @@ +# Final Task Final Task for EPAM Python Training by Sholomitski Dmitry + +I am proposed to implement Python RSS-reader using python 3.10. + +RSS reader is a command-line utility which receives RSS URL and prints results in human-readable format. Format of the news console output: $ rss_reader.py https://people.onliner.by/feed + +``` +channel title: Лайфстайл Onlíner +channel link: https://people.onliner.by/ +************************************************************************************************************************ +Title: В шестнадцать лет выиграла Олимпиаду, а в семнадцать — попалась на магазинной краже. Рассказываем о несчастливом вундеркинде женского тенниса (спецпроект) +Description: Богатые тоже плачут. Даже если они успешны, знамениты и обожаемы сотнями тысяч поклонников. Это относится и к американской теннисистке Дженнифер Каприати, которую снабдила талантом сама природа. Еще в подростковом возрасте спортсменка начала выносить взрослых соперниц. Уже в девять лет юной Дженни предлагали сотрудничество производители теннисной формы и снаряжения. А ведущие американские СМИ стали наблюдать за карьерой Каприати задолго до того, как теннисистка окончила школу. Вместе с BETERA в нашем спортивном проекте рассказываем, как «золотая» девочка из спорта докатилась до магазинной кражи, марихуаны и мыслей о суициде.Читать далее… +Published: 2022-06-30 16:11:31 +Image: https://content.onliner.by/news/thumbnail/19f511e02774f2c9d0c7d74e66342dbb.jpeg +Read more: https://people.onliner.by/2022/06/30/vunderkind +------------------------------------------------------------------------------------------------------------------------ +``` + +The program has the following settings, which can be applied together or separately +``` +-h, --help show this help message and exit +--version Print version info and exit +--json Save result as in JSON file +--limit LIMIT Limit news if this parameter provided +-v, --verbose Output verbose messages +--date DATE Gets a date in YYYYMMDD format. Print news from the specified date. +--to-html Convert news to HTML file (provide path to folder where save export file) +--to-pdf Convert news to PDF file (provide path to folder where save export file) +--colorize Enables colored output mode +``` + + + + +Utility provides the following interface: usage: rss_reader.py source [-h] [--version] [--json] [--verbose] [--limit LIMIT] [--date] [--to-html] [--to-pdf] [--colorize ] + +Pure Python command-line RSS reader. + +positional arguments: source Input your RSS-link hear. Your link have to start with "https://" + +JSON option prints news to stdout. Example: + +``` +{ + "rss_url": "https://people.onliner.by/feed", + "channel_title": "Лайфстайл Onlíner", + "channel_link": "https://people.onliner.by/", + "item_title": "Украина, 126-й день", + "item_pubdate": "2022-06-29 08:08:45", + "item_description": "Вчера Минобороны России объяснило, что произошло в украинском Кременчуге: с самолетов высокоточным оружием был обстрелян склад с американской техникой. Украинское Минобороны публикует все новые снимки поставок... Продолжаем хронику. Читать далее…", + "item_link": "https://people.onliner.by/2022/06/29/ukraina-126-j-den", + "item_image": "https://content.onliner.by/news/thumbnail/1fee0b8254c5c24cf728800331bf6f5a.jpeg" +} +``` +## Installing the package (if Python is installed, check the version python=3.10) + + +``` +create a folder, put files fo folder +create a virtual environment +download virtualenv for win 'pip install virtualenv' and for Ubuntu 'sudo apt-get install python3-venv' +create the env for win 'python -m venv venv' and for linux '/usr/bin/python3 -m venv env') +activate the environment (for win 'env\Scripts\activate.bat', for Ubuntu 'source env/bin/activate') +pip install -r requirements.txt +pip setup.py install in folder with files +The package is ready to use +``` + +### Note: if you are using Apple MacBook (or iMac) with M1(ARM) CPU converting to PDF works without pictures. It is bug of ARM architecture \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_1.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_1.txt new file mode 100644 index 00000000..88d62cc6 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_1.txt @@ -0,0 +1,8 @@ +[{'channel_link': 'https://www.yahoo.com/news', + 'channel_title': 'Yahoo News - Latest News Headlines', + 'item_description': 'Description not provided', + 'item_image': 'https://s.yimg.com/uu/api/res/1.2/Kn3F_gIJwe0a3uIOU.Tb2w--~B/aD0yMzgxO3c9MzU3MTthcHBpZD15dGFjaHlvbg--/https://media.zenfs.com/en/ap.org/4a35cff443aaabc2b49d94a5e7672369', + 'item_link': 'https://news.yahoo.com/spit-disrespect-arrive-wimbledon-tennis-220151441.html', + 'item_pubdate': '2022-06-28 22:01:51', + 'item_title': "Spit, 'disrespect' arrive at Wimbledon as tennis turns ugly", + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_10.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_10.txt new file mode 100644 index 00000000..1f7597da --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_10.txt @@ -0,0 +1,10 @@ +[{'channel_link': 'https://www.bbc.co.uk/news/', + 'channel_title': 'BBC News - World', + 'item_description': "According to US intelligence assessments, Russia's " + 'invasion is likely to grind on for some time.', + 'item_image': 'image is not provided', + 'item_link': 'https://www.bbc.co.uk/news/world-europe-61990495?at_medium=RSS&at_campaign=KARANGA', + 'item_pubdate': '2022-06-30 03:00:59', + 'item_title': 'Russia invasion: Putin still wants to take most of Ukraine - ' + 'US', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_11.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_11.txt new file mode 100644 index 00000000..0ebc4698 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_11.txt @@ -0,0 +1,10 @@ +[{'channel_link': 'https://vse.sale/', + 'channel_title': 'Газета ВСЁ', + 'item_description': 'Празднование Дня города прошло на высоком уровне - была ' + 'составлена насыщенная программа, соблюдались меры ' + 'безопасности и контроля, оперативно убран мусор.', + 'item_image': 'image is not provided', + 'item_link': 'https://vse.sale/news/view/37519', + 'item_pubdate': '2022-06-28 19:52:00', + 'item_title': 'Проблема перегороженных улиц', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_2.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_2.txt new file mode 100644 index 00000000..aafc6eae --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_2.txt @@ -0,0 +1,18 @@ +[{'channel_link': 'https://news.google.com/?hl=en-US=US=US:en', + 'channel_title': 'Top stories - Google News', + 'item_description': 'Liz Cheney Calls Trump ‘a Domestic Threat That We Have ' + 'Never Faced Before’The New York TimesLiz Cheney says US ' + "is 'confronting a domestic threat' in Donald " + 'TrumpCNNOpinion | Trump wanted loyalty above all. He ' + 'got just the opposite.The Washington PostMSNBC’s ' + "Nicolle Wallace says Liz Cheney is targeting 'Trumpism' " + 'like her father targeted terrorism after 9/11Fox ' + 'NewsRepublicans must choose Trump or the Constitution, ' + "Liz Cheney warns, describing 'threat' like no otherABC " + 'News', + 'item_image': 'image is not provided', + 'item_link': 'https://news.google.com/__i/rss/rd/articles/CBMiS2h0dHBzOi8vd3d3Lm55dGltZXMuY29tLzIwMjIvMDYvMjkvdXMvcG9saXRpY3MvbGl6LWNoZW5leS1zcGVlY2gtdHJ1bXAuaHRtbNIBAA?oc=5', + 'item_pubdate': '2022-06-30 03:02:32', + 'item_title': 'Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never ' + 'Faced Before’ - The New York Times', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_3.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_3.txt new file mode 100644 index 00000000..46b1e1f9 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_3.txt @@ -0,0 +1,11 @@ +[{'channel_link': 'https://www.nytimes.com/section/world', + 'channel_title': 'NYT > World News', + 'item_description': 'Applying the lessons of taekwondo, the regional ' + 'military leader has rallied the embattled southern city ' + 'of Mykolaiv.', + 'item_image': 'image is not provided', + 'item_link': 'https://www.nytimes.com/2022/06/30/world/europe/ukraine-vitaliy-kim-mykolaiv.html', + 'item_pubdate': '2022-06-30 09:00:24', + 'item_title': 'Vitaliy Kim, Master Motivator and Symbol of Ukraine’s ' + 'Resistance', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_4.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_4.txt new file mode 100644 index 00000000..dc1f6988 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_4.txt @@ -0,0 +1,10 @@ +[{'channel_link': 'https://www.cnbc.com/id/100727362/device/rss/rss.html', + 'channel_title': 'International: Top News And Analysis', + 'item_description': 'The trip is for the 25th anniversary on Friday of Hong ' + "Kong's handover to China from British colonial rule.", + 'item_image': 'image is not provided', + 'item_link': 'https://www.cnbc.com/2022/06/30/chinas-xi-arrives-in-hong-kong-in-first-trip-off-mainland-since-pandemic.html', + 'item_pubdate': '2022-06-30 08:48:08', + 'item_title': "China's Xi arrives in Hong Kong in his first trip off the " + 'mainland since the onset of the pandemic', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_5.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_5.txt new file mode 100644 index 00000000..47b6633e --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_5.txt @@ -0,0 +1,12 @@ +[{'channel_link': 'https://www.cbsnews.com/', + 'channel_title': 'World - CBSNews.com', + 'item_description': 'Amid the war in Ukraine, President Biden said Wednesday ' + 'the U.S. will send more military might to nine European ' + 'countries. Russia threatened to respond with ' + '"compensatory measures." Nancy Cordes has the latest ' + 'from the NATO summit in Madrid.', + 'item_image': 'https://assets2.cbsnewsstatic.com/hub/i/r/2022/06/29/4c08cced-c8b0-4cdc-be3e-10d01c731850/thumbnail/60x60/51f8a9de3eb98a1bb06411e3c6384409/cbsn-fusion-us-to-increase-its-military-presence-in-europe-thumbnail-1096498-640x360.jpg', + 'item_link': 'https://www.cbsnews.com/video/us-to-increase-its-military-presence-in-europe/', + 'item_pubdate': '2022-06-29 22:12:47', + 'item_title': 'U.S. to increase its military presence in Europe', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_6.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_6.txt new file mode 100644 index 00000000..0a5a2e38 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_6.txt @@ -0,0 +1,11 @@ +[{'channel_link': 'https://www.nytimes.com', + 'channel_title': 'NYT > Top Stories', + 'item_description': 'A reluctance by some liberal district attorneys to ' + 'bring criminal charges against abortion providers is ' + 'already complicating the legal landscape in some ' + 'states.', + 'item_image': 'https://static01.nyt.com/images/2022/06/29/us/29abortion-enforcement03/29abortion-enforcement03-moth.jpg', + 'item_link': 'https://www.nytimes.com/2022/06/29/us/abortion-enforcement-prosecutors.html', + 'item_pubdate': '2022-06-29 21:41:55', + 'item_title': 'In States Banning Abortion, a Growing Rift Over Enforcement', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_7.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_7.txt new file mode 100644 index 00000000..f0726e82 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_7.txt @@ -0,0 +1,11 @@ +[{'channel_link': 'https://auto.onliner.by/', + 'channel_title': 'Авто Onlíner', + 'item_description': 'Вчера вечером в самом центре Бобруйска на автостоянку ' + 'упало дерево. В этот момент здесь стоял кроссовер ' + 'Hyundai, внутри которого находилась женщина-водитель. ' + 'Подробности пишет сайт Komkur.info.Читать далее…', + 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg', + 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', + 'item_pubdate': '2022-06-30 11:48:45', + 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_8.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_8.txt new file mode 100644 index 00000000..1f7597da --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_8.txt @@ -0,0 +1,10 @@ +[{'channel_link': 'https://www.bbc.co.uk/news/', + 'channel_title': 'BBC News - World', + 'item_description': "According to US intelligence assessments, Russia's " + 'invasion is likely to grind on for some time.', + 'item_image': 'image is not provided', + 'item_link': 'https://www.bbc.co.uk/news/world-europe-61990495?at_medium=RSS&at_campaign=KARANGA', + 'item_pubdate': '2022-06-30 03:00:59', + 'item_title': 'Russia invasion: Putin still wants to take most of Ukraine - ' + 'US', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_9.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_9.txt new file mode 100644 index 00000000..e8d599a6 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_files/dict_9.txt @@ -0,0 +1,12 @@ +[{'channel_link': 'https://www.buzzfeednews.com', + 'channel_title': 'BuzzFeed News', + 'item_description': 'The policy prohibiting girls from attending school ' + 'after sixth grade contradicts the regime’s previous ' + 'promises to loosen restrictions on education ' + 'rights.View Entire Post ›', + 'item_image': 'https://img.buzzfeed.com/buzzfeed-static/static/2022-06/13/19/campaign_images/c453b771f93f/she-was-one-year-away-from-going-to-college-then--2-778-1655149050-7_dblbig.jpg', + 'item_link': 'https://www.buzzfeednews.com/article/syedzabiullah/afghanistan-taliban-girls-school-ban', + 'item_pubdate': '2022-06-13 20:32:05', + 'item_title': 'She Was One Year Away From Going To College. Then The Taliban ' + 'Banned Her From School.', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/dict_for_print.txt b/Sholomitski Dmitry/rss_reader/Tests_files/dict_for_print.txt new file mode 100644 index 00000000..9d64669b --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/dict_for_print.txt @@ -0,0 +1,103 @@ +[{'channel_link': 'https://www.yahoo.com/news', + 'channel_title': 'Yahoo News - Latest News Headlines', + 'item_description': 'Description not provided', + 'item_image': 'https://s.yimg.com/uu/api/res/1.2/Kn3F_gIJwe0a3uIOU.Tb2w--~B/aD0yMzgxO3c9MzU3MTthcHBpZD15dGFjaHlvbg--/https://media.zenfs.com/en/ap.org/4a35cff443aaabc2b49d94a5e7672369', + 'item_link': 'https://news.yahoo.com/spit-disrespect-arrive-wimbledon-tennis-220151441.html', + 'item_pubdate': '2022-06-28 22:01:51', + 'item_title': "Spit, 'disrespect' arrive at Wimbledon as tennis turns ugly", + 'rss_url': 'https://test_url.com/xml'}, {'channel_link': 'https://www.bbc.co.uk/news/', + 'channel_title': 'BBC News - World', + 'item_description': "According to US intelligence assessments, Russia's " + 'invasion is likely to grind on for some time.', + 'item_image': 'image is not provided', + 'item_link': 'https://www.bbc.co.uk/news/world-europe-61990495?at_medium=RSS&at_campaign=KARANGA', + 'item_pubdate': '2022-06-30 03:00:59', + 'item_title': 'Russia invasion: Putin still wants to take most of Ukraine - ' + 'US', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://news.google.com/?hl=en-US=US=US:en', + 'channel_title': 'Top stories - Google News', + 'item_description': 'Liz Cheney Calls Trump ‘a Domestic Threat That We Have ' + 'Never Faced Before’The New York TimesLiz Cheney says US ' + "is 'confronting a domestic threat' in Donald " + 'TrumpCNNOpinion | Trump wanted loyalty above all. He ' + 'got just the opposite.The Washington PostMSNBC’s ' + "Nicolle Wallace says Liz Cheney is targeting 'Trumpism' " + 'like her father targeted terrorism after 9/11Fox ' + 'NewsRepublicans must choose Trump or the Constitution, ' + "Liz Cheney warns, describing 'threat' like no otherABC " + 'News', + 'item_image': 'image is not provided', + 'item_link': 'https://news.google.com/__i/rss/rd/articles/CBMiS2h0dHBzOi8vd3d3Lm55dGltZXMuY29tLzIwMjIvMDYvMjkvdXMvcG9saXRpY3MvbGl6LWNoZW5leS1zcGVlY2gtdHJ1bXAuaHRtbNIBAA?oc=5', + 'item_pubdate': '2022-06-30 03:02:32', + 'item_title': 'Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never ' + 'Faced Before’ - The New York Times', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://www.nytimes.com/section/world', + 'channel_title': 'NYT > World News', + 'item_description': 'Applying the lessons of taekwondo, the regional ' + 'military leader has rallied the embattled southern city ' + 'of Mykolaiv.', + 'item_image': 'image is not provided', + 'item_link': 'https://www.nytimes.com/2022/06/30/world/europe/ukraine-vitaliy-kim-mykolaiv.html', + 'item_pubdate': '2022-06-30 09:00:24', + 'item_title': 'Vitaliy Kim, Master Motivator and Symbol of Ukraine’s ' + 'Resistance', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://www.cnbc.com/id/100727362/device/rss/rss.html', + 'channel_title': 'International: Top News And Analysis', + 'item_description': 'The trip is for the 25th anniversary on Friday of Hong ' + "Kong's handover to China from British colonial rule.", + 'item_image': 'image is not provided', + 'item_link': 'https://www.cnbc.com/2022/06/30/chinas-xi-arrives-in-hong-kong-in-first-trip-off-mainland-since-pandemic.html', + 'item_pubdate': '2022-06-30 08:48:08', + 'item_title': "China's Xi arrives in Hong Kong in his first trip off the " + 'mainland since the onset of the pandemic', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://auto.onliner.by/', + 'channel_title': 'Авто Onlíner', + 'item_description': 'Вчера вечером в самом центре Бобруйска на автостоянку ' + 'упало дерево. В этот момент здесь стоял кроссовер ' + 'Hyundai, внутри которого находилась женщина-водитель. ' + 'Подробности пишет сайт Komkur.info.Читать далее…', + 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg', + 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', + 'item_pubdate': '2022-06-30 11:48:45', + 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://auto.onliner.by/', + 'channel_title': 'Авто Onlíner', + 'item_description': 'ДОБАВИЛ 1 Вчера вечером в самом центре Бобруйска на автостоянку ' + 'упало дерево. В этот момент здесь стоял кроссовер ' + 'Hyundai, внутри которого находилась женщина-водитель. ' + 'Подробности пишет сайт Komkur.info.Читать далее…', + 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg', + 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', + 'item_pubdate': '2022-06-30 11:48:45', + 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://auto.onliner.by/', + 'channel_title': 'Авто Onlíner', + 'item_description': 'ДОБАВИЛ 2 Вчера вечером в самом центре Бобруйска на автостоянку ' + 'упало дерево. В этот момент здесь стоял кроссовер ' + 'Hyundai, внутри которого находилась женщина-водитель. ' + 'Подробности пишет сайт Komkur.info.Читать далее…', + 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg', + 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', + 'item_pubdate': '2022-06-30 11:48:45', + 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://auto.onliner.by/', + 'channel_title': 'Авто Onlíner', + 'item_description': 'ДОБАВИЛИ 3 Вчера вечером в самом центре Бобруйска на автостоянку ' + 'упало дерево. В этот момент здесь стоял кроссовер ' + 'Hyundai, внутри которого находилась женщина-водитель. ' + 'Подробности пишет сайт Komkur.info.Читать далее…', + 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg', + 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', + 'item_pubdate': '2022-06-30 11:48:45', + 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', + 'rss_url': 'https://test_url.com/xml'},{'channel_link': 'https://auto.onliner.by/', + 'channel_title': 'Авто Onlíner', + 'item_description': 'ДОБАВИЛИ 4 Вчера вечером в самом центре Бобруйска на автостоянку ' + 'упало дерево. В этот момент здесь стоял кроссовер ' + 'Hyundai, внутри которого находилась женщина-водитель. ' + 'Подробности пишет сайт Komkur.info.Читать далее…', + 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg', + 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', + 'item_pubdate': '2022-06-30 11:48:45', + 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', + 'rss_url': 'https://test_url.com/xml'}] \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/html_file.html b/Sholomitski Dmitry/rss_reader/Tests_files/html_file.html new file mode 100644 index 00000000..d35ab3c8 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/html_file.html @@ -0,0 +1,138 @@ + + + + +Formatted RSS News + +

Channel's title: Yahoo News - Latest News Headlines

+

Link to channel: https://www.yahoo.com/news

+
+ +
+

Spit, 'disrespect' arrive at Wimbledon as tennis turns ugly

+ +

Description not provided

+ +

Published at: 2022-06-28 22:01:51

+ +

Read more

+

Channel's title: BBC News - World

+

Link to channel: https://www.bbc.co.uk/news/

+
+ +
+

Russia invasion: Putin still wants to take most of Ukraine - US

+ +

According to US intelligence assessments, Russia's invasion is likely to grind on for some time.

+ +

Published at: 2022-06-30 03:00:59

+ +

Read more

+

Channel's title: Top stories - Google News

+

Link to channel: https://news.google.com/?hl=en-US=US=US:en

+
+ +
+

Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never Faced Before’ - The New York Times

+ +

Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never Faced Before’The New York TimesLiz Cheney says US is 'confronting a domestic threat' in Donald TrumpCNNOpinion | Trump wanted loyalty above all. He got just the opposite.The Washington PostMSNBC’s Nicolle Wallace says Liz Cheney is targeting 'Trumpism' like her father targeted terrorism after 9/11Fox NewsRepublicans must choose Trump or the Constitution, Liz Cheney warns, describing 'threat' like no otherABC News

+ +

Published at: 2022-06-30 03:02:32

+ +

Read more

+

Channel's title: NYT > World News

+

Link to channel: https://www.nytimes.com/section/world

+
+ +
+

Vitaliy Kim, Master Motivator and Symbol of Ukraine’s Resistance

+ +

Applying the lessons of taekwondo, the regional military leader has rallied the embattled southern city of Mykolaiv.

+ +

Published at: 2022-06-30 09:00:24

+ +

Read more

+

Channel's title: International: Top News And Analysis

+

Link to channel: https://www.cnbc.com/id/100727362/device/rss/rss.html

+
+ +
+

China's Xi arrives in Hong Kong in his first trip off the mainland since the onset of the pandemic

+ +

The trip is for the 25th anniversary on Friday of Hong Kong's handover to China from British colonial rule.

+ +

Published at: 2022-06-30 08:48:08

+ +

Read more

+

Channel's title: Авто Onlíner

+

Link to channel: https://auto.onliner.by/

+
+ +
+

В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра

+ +

Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…

+ +

Published at: 2022-06-30 11:48:45

+ +

Read more

+
+ +
+

В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра

+ +

ДОБАВИЛ 1 Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…

+ +

Published at: 2022-06-30 11:48:45

+ +

Read more

+
+ +
+

В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра

+ +

ДОБАВИЛ 2 Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…

+ +

Published at: 2022-06-30 11:48:45

+ +

Read more

+
+ +
+

В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра

+ +

ДОБАВИЛИ 3 Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…

+ +

Published at: 2022-06-30 11:48:45

+ +

Read more

+
+ +
+

В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра

+ +

ДОБАВИЛИ 4 Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…

+ +

Published at: 2022-06-30 11:48:45

+ +

Read more

+
\ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/test_archive_dict.txt b/Sholomitski Dmitry/rss_reader/Tests_files/test_archive_dict.txt new file mode 100644 index 00000000..2e527f06 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/test_archive_dict.txt @@ -0,0 +1 @@ +[{'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'В чем польза клубники и в каких объемах ее стоит есть? Поговорили с экспертом', 'item_pubdate': '2022-06-30 15:00:07', 'item_description': 'Июнь — время повальной клубникомании в Беларуси. Ягоду по стране скупают тоннами, а за раз некоторые съедают килограммами — со сливками, сметаной и без. Мы, в свою очередь, пообщались с нутрициологом Юлией Айзенман и узнали, в чем польза клубники, сколько ее можно лопать за раз и с чем сочетать.Читать далее…', 'item_link': 'https://people.onliner.by/2022/06/30/v-chem-polza-klubniki-i-v-kakix-obemax-ee-stoit-est-pogovorili-s-ekspertom', 'item_image': 'https://content.onliner.by/news/thumbnail/64d367e28f703264c080c082342edb8f.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'В Минске на пляже пропал 26-летний парень. Его ищут третьи сутки', 'item_pubdate': '2022-06-30 14:47:13', 'item_description': 'В понедельник вечером, около 22:00, пропал Платонов Валерий Ильич. Парню — 26 лет, в этот день он находился на 3-м или 4-м пляже Цнянского водохранилища. Был не один, но ушел от компании в неизвестном направлении. До настоящего времени о его местонахождении ничего не известно.Читать далее…', 'item_link': 'https://people.onliner.by/opinions/2022/06/30/v-minske-na-plyazhe-propal-26-letnij-paren-ego-ishhut-treti-sutki', 'item_image': 'https://content.onliner.by/news/thumbnail/a8bc208805788bd5d9943504522a1737.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Криптовалюта продолжает падать, но аналитики уже видят дно', 'item_pubdate': '2022-06-30 14:26:36', 'item_description': 'Курс основных криптовалют продолжает падение. Стоимость биткоина за сутки упала почти на 5%, а Etherium — на 10%. Первая торгуется ниже $19 тысяч за монету, вторая еле-еле удерживается у отметки $1000. Тем не менее аналитики сохраняют оптимизм.Читать далее…', 'item_link': 'https://tech.onliner.by/2022/06/30/kriptovalyuta-prodolzhaet-padat-no-analitiki-uzhe-vidyat-dno', 'item_image': 'https://content.onliner.by/news/thumbnail/56a9dfb4b9ce34c87dc993496a4b1c07.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Названы самые качественные автомобили 2022 года. Это не японские модели', 'item_pubdate': '2022-06-30 14:00:32', 'item_description': 'Американское агентство J.D. Power славится своими рейтингами качества автомобилей. Вот их отчет по моделям 2022 модельного года. Как и в прошлые разы, рейтинг составляли на основе жалоб реальных владельцев (среднее количество жалоб на 100 автомобилей). Учитывались даже мелкие проблемы.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/nazvany-samye-kachestvennye-avtomobili-2022-goda-eto-ne-yaponskie-modeli', 'item_image': 'https://content.onliner.by/news/thumbnail/81a819eff6e84e0c54cd276c0b4b18ae.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Лимит для посылок в 22 евро отменяется', 'item_pubdate': '2022-06-30 13:56:47', 'item_description': 'С 1 июля Совмин отменяет лимит в 22 евро на посылки из иностранных интернет-магазинов, сообщает Национальный правовой портал.\r\n\r\nЧитать далее…', 'item_link': 'https://money.onliner.by/2022/06/30/limit-dlya-posylok-v-22-evro-otmenyaetsya', 'item_image': 'https://content.onliner.by/news/thumbnail/0c2c4f32182081a201bf9aa15d3d0d6d.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Пытался угнать машину как в кино. Но что-то пошло не так', 'item_pubdate': '2022-06-30 13:51:36', 'item_description': 'Прогуливаясь со своим приятелем по столице, житель Жлобина обратил внимание на припаркованную возле дома машину и решил угнать ее, рассказали в ГУВД Мингорисполкома. Использовал подсмотренный в кино способ. Однако попытка не увенчалась успехом.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/ugon-62', 'item_image': 'https://content.onliner.by/news/thumbnail/acfde84f285a1322b723477360328052.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Удара не было, а ДТП есть. Это как? (видео)', 'item_pubdate': '2022-06-30 13:22:12', 'item_description': 'Мужчина в Гродно проезжал перекресток на зеленый сигнал светофора. Неожиданно справа появились «спортивные» «Жигули» и двинулись наперерез. Обе машины успели затормозить в центре перекрестка, столкновения не было. И тем не менее было оформлено ДТП. Что же случилось?Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/grodnodtp', 'item_image': 'https://content.onliner.by/news/thumbnail/c3febd45d340b586e36a0338ac4cf74c.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Завтра снова можно будет летать в Китай из Минска', 'item_pubdate': '2022-06-30 13:12:17', 'item_description': 'С 1 июля авиакомпания Air China возобновляет полеты в Минск, об этом сообщила пресс-служба Национального аэропорта. Рейсы из Минска в Китай будут выполняться по пятницам на самолете Airbus A-330.Читать далее…', 'item_link': 'https://people.onliner.by/2022/06/30/kitaj-vozobnovlyaet-aviaperevozki-s-minskom-s-1-iyulya', 'item_image': 'https://content.onliner.by/news/thumbnail/685f8d4d286851a3cec8fe1eda6cf31c.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Больше не 4 копейки за кВт·ч при «подогреве» дома электричеством. Тарифы на тепло и свет изменились', 'item_pubdate': '2022-06-30 12:55:31', 'item_description': 'Такое случается нечасто, так что можно достать из холодильника бутылочку лимонада и отпраздновать. Тарифы на тепловую и электроэнергию стали хоть чуточку, но меньше. О приятных изменениях, которые нас ждут, сообщает Национальный правовой портал pravo.by, ссылаясь на постановление Совмина от 29 июня 2022 года №421. Указанные тарифы будут действовать в период с 1 июня по 31 декабря 2022-го. Читать далее…', 'item_link': 'https://realt.onliner.by/2022/06/30/tarify-na-teplo-i-svet-izmenilis-i-budut-takimi-do-31-dekabrya', 'item_image': 'https://content.onliner.by/news/thumbnail/db6c5fc15aea64cf5dde770626ecc415.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Можно, если осторожно? Имеют ли право коммунальщики устроить «большой покос» в выходные с утра пораньше', 'item_pubdate': '2022-06-30 12:16:45', 'item_description': 'Лето — прекрасная пора, омрачить которую могут разве что разноголосые триммеры и газонокосилки. Любому из нас знакомо это выматывающее душу жужжание, когда несколько часов подряд у тебя под окнами стригут-подравнивают траву на микроскопической полянке. Так ведь и начинают «бойцы» с утра пораньше (что, в общем-то, понятно, ведь трудиться в полной экипировке на солнцепеке — прямой путь к тепловому удару).Читать далее…', 'item_link': 'https://realt.onliner.by/2022/06/30/bolshoj-pokos-v-vyxodnye', 'item_image': 'https://content.onliner.by/news/thumbnail/c908a4b93bfa32755e18cda136a35289.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Литовская железная дорога ответила, будет ли возобновлять пассажирские перевозки с Минском', 'item_pubdate': '2022-06-30 12:14:09', 'item_description': 'На этой неделе Минтранс высказался о возобновлении движения поездов в Польшу, Литву и Латвию. Ответ литовской стороны не заставил долго ждать. В компании Литовские железные дороги (Lietuvos gelezinkeliai, LTG) говорят, что ни в этом, ни в следующем году таких планов у них нет.Читать далее…', 'item_link': 'https://people.onliner.by/2022/06/30/vilnyus-otvetil-chto-poka', 'item_image': 'https://content.onliner.by/news/thumbnail/aa83ead9b8d369b7a54e7bafac8ab2ee.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Акции российского «Газпрома» рухнули на 30%', 'item_pubdate': '2022-06-30 12:01:43', 'item_description': 'Потому что на годовом собрании российская компания решила не выплачивать дивиденды за 2021 год. А они должны были быть рекордными из-за роста цен на ресурс во всем мире.Читать далее…', 'item_link': 'https://money.onliner.by/2022/06/30/akcii-rossijskogo-gazproma-ruxnuli-na-30', 'item_image': 'https://content.onliner.by/news/thumbnail/1dacbd60b8828a14a7bc9fe5417b336b.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Samsung выпустила защищенный смартфон Galaxy XCover6 Pro', 'item_pubdate': '2022-06-30 12:00:00', 'item_description': 'Samsung выпустила смартфон Galaxy XCover6 Pro, защищенный от разных неприятностей. Корпус — из толстого пластика, дисплей защищен Corning Gorilla Glass Victus+. Заявлена защита по стандартам MIL-STD-810H и IP68. То есть телефон можно мочить и даже немножко и аккуратно ронять.Читать далее…', 'item_link': 'https://tech.onliner.by/2022/06/30/samsung-vypustila-zashhishhennyj-smartfon-galaxy-xcover6-pro', 'item_image': 'https://content.onliner.by/news/thumbnail/7a8445f83c37fd7d1026aa6c575309dc.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Тополь упал на машину, когда в ней находилась водитель', 'item_pubdate': '2022-06-30 11:48:45', 'item_description': 'Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Вышла последняя песня Юрия Шатунова', 'item_pubdate': '2022-06-30 11:38:49', 'item_description': 'Последняя песня Юрия Шатунова, скончавшегося 23 июня от остановки сердца, появилась на его YouTube-канале на следующие сутки после похорон. Продюсер исполнителя Аркадий Кудряшов рассказал, что это не единственная невыпущенная песня.Читать далее…', 'item_link': 'https://people.onliner.by/2022/06/30/vyshla-poslednyaya-pesny', 'item_image': 'https://content.onliner.by/news/thumbnail/6f5e6b45c9784a8f50963fd6569d8f4c.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Французский ë-мобиль. У Citroen появился странный фастбэк С4 X', 'item_pubdate': '2022-06-30 11:34:17', 'item_description': 'Компания Citroen рассекретила фастбэк повышенной проходимости C4 X. Машина призвана стать любимчиком у тех, кто выбирает между хетчбэками и кроссоверами. В линейке Citroen модель займет промежуточное положение между C4 и C5 X.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/francuzskij-e-mobil-u-citroen-poyavilsya-strannyj-fastbek-s4-x', 'item_image': 'https://content.onliner.by/news/thumbnail/d468825ef9c1d8024905dbceda60445d.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Владелец дома заменил в нем окна и получил огромный штраф', 'item_pubdate': '2022-06-30 11:33:41', 'item_description': 'С первого взгляда эта история выглядит как иллюстрация тезиса о наказуемости инициативы. Владелец большого трехэтажного особняка решил заменить в нем окна и в итоге будет вынужден заплатить местным властям штраф в $60 тыс. Однако у чиновников есть своя логика, пишет The Sun.Читать далее…', 'item_link': 'https://realt.onliner.by/2022/06/30/vladelec-doma-zamenil-v-nem-okna-i-poluchil-ogromnyj-shtraf', 'item_image': 'https://content.onliner.by/news/thumbnail/06e4473a803bf49e00b60cdbe26fadeb.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Обладатель трех премий «Грэмми» Ар Келли получил 30 лет тюрьмы. Что он натворил?', 'item_pubdate': '2022-06-30 11:30:30', 'item_description': 'В сентябре прошлого года суд присяжных в Нью-Йорке признал виновным в рэкете и торговле людьми ради секса поп-исполнителя, трехкратного обладателя премии «Грэмми» Ар Келли. На суде потерпевшие рассказали, что он требовал от них строгого соблюдения правил, таких как спрашивать его разрешения поесть или сходить в туалет, а также написать «письма с извинениями», которые якобы оправдывают его проступки.Читать далее…', 'item_link': 'https://people.onliner.by/2022/06/30/obladatel-trex-premij-gremmi', 'item_image': 'https://content.onliner.by/news/thumbnail/30ab2e329837ab78fdec9127ac53cd3b.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'В Беларуси будут судить дальнобойщика, допустившего серьезное ДТП в Чехии', 'item_pubdate': '2022-06-30 11:17:07', 'item_description': '34-летнего мужчину, профессионального водителя грузовика, подозревают в нарушении ПДД, повлекшем по неосторожности причинение тяжких травм. Причем у гособвинения есть сведения, что он был пьян в момент аварии. Примечательно в этом деле то, что ДТП случилось в Чехии, а дело направлено в суд белорусской столицы.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/v-belarusi-budut-sudit-dalnobojshhika-dopustivshego-sereznoe-dtp-v-chexii', 'item_image': 'https://content.onliner.by/news/thumbnail/e192da250d96e394249af53797007709.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Для поклонников «Звездных войн» сделали коктейль за $5000', 'item_pubdate': '2022-06-30 11:00:29', 'item_description': '$5000 — огромная цена для напитка. Тем не менее в «Диснее» рассчитывают, что кто-нибудь когда-нибудь будет покупать коктейль за эту цену. При этом получить его не так уж просто — для этого нужно купить место на круизом лайнере Disney Wish. Это новый развлекательный корабль компании, который начнет курсировать со дня на день.Читать далее…', 'item_link': 'https://tech.onliner.by/2022/06/30/dlya-poklonnikov-zvezdnyx-vojn-sdelali-koktejl-za-5000', 'item_image': 'https://content.onliner.by/news/thumbnail/0439be4d7794882c6f22ea35fe09c035.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Доллар и евро рванули вперед (обновлено)', 'item_pubdate': '2022-06-30 10:36:52', 'item_description': 'В этом году курсы валют делают удивительное: на днях сотня российских рублей подобралась к курсу в 5 белорусских, а доллар и евро после мартовского скачка продолжают плавное падение и почти сравнялись. Но и тут бывают резкие повороты: на торгах в четверг все пошло не по плану.Читать далее…', 'item_link': 'https://money.onliner.by/2022/06/30/dollar-i-evro-rvanuli-vpered-2', 'item_image': 'https://content.onliner.by/news/thumbnail/80fb89e62fe7ed22c319a9ce61a078fe.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'В Минобороны рассказали, что за самолеты летают над жилыми домами (видео)', 'item_pubdate': '2022-06-30 10:29:24', 'item_description': 'Вчера вечером читатели стали сообщать о самолетах над жилыми домами. Спать они-то не мешают, но людям просто интересно, что к чему. Сегодня в Минобороны рассказали, что это было.Читать далее…', 'item_link': 'https://people.onliner.by/2022/06/30/chto-za-samolety-letayut-nad', 'item_image': 'https://content.onliner.by/news/thumbnail/50ebfbd5e2577496e978045f7e7ab125.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Пришли погулять — сломали калитку. Как ведут себя незваные гости в «Новой Боровой»', 'item_pubdate': '2022-06-30 10:04:51', 'item_description': 'Люди тянутся к прекрасному. Поэтому в «Новую Боровую» периодически приезжают погулять минчане из других районов. Самые отчаянные даже пытаются проникнуть в закрытые дворы — недоступное так и манит. Но не всегда «дружеские» визиты заканчиваются только созерцанием, порой «представители» районов откровенно вандалят. Вот каким видео с Onlíner поделились жители стильного квартала.Читать далее…', 'item_link': 'https://realt.onliner.by/2022/06/30/prishli-pogulyat-slomali-kalitku-kak-vedut-sebya-nezvanye-gosti-v-novoj-borovoj', 'item_image': 'https://content.onliner.by/news/thumbnail/fdab7f1337bda8702323c1b17ff5387a.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'В результате ДТП сгорела Mazda. Водитель не выбрался из огня', 'item_pubdate': '2022-06-30 10:03:19', 'item_description': 'Сегодня утром стало известно об ужасной аварии, случившейся под Гомелем. Как сообщили в региональной ГАИ, около часа ночи в результате наезда на препятствие загорелся автомобиль. В салоне было двое юношей. Водитель не смог выбраться из огня, пассажир выжил, но получил серьезные травмы.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/v-rezultate-dtp-sgorela-mazda-voditel-pogib-passazhir-postradal', 'item_image': 'https://content.onliner.by/news/thumbnail/f87c2a8b386c5c5a986369c14b21a5cf.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Производство авто в России сократилось почти на 97%. Это исторический антирекорд', 'item_pubdate': '2022-06-30 10:01:12', 'item_description': 'Росстат продолжает сыпать соль на рану автомобильного рынка РФ. За пять месяцев текущего года с российских автозаводов сошло 268 тыс. легковых автомобилей. Это на 56,4% ниже показателя за аналогичный период прошлого года.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/proizvodstvo-avto-v-rossii-sokratilos-pochti-na-97-eto-istoricheskij-antirekord', 'item_image': 'https://content.onliner.by/news/thumbnail/5ab7c55e266ff82dfeb93e79567223a7.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Посмотрите на iPhone за $500 тысяч', 'item_pubdate': '2022-06-30 10:00:38', 'item_description': 'Сегодня исполняется 15 лет с тех пор как вышел первый iPhone. В честь такого события блогер Люк Миани решил показать несколько самых ранних и редких прототипов первого «яблочного» телефона. Стоимость каждого такого прототипа сегодня составляет около полумиллиона долларов.Читать далее…', 'item_link': 'https://tech.onliner.by/2022/06/30/posmotrite-na-iphone-za-500-tysyach', 'item_image': 'https://content.onliner.by/news/thumbnail/4684a8124861dd683ae9112e7cc2992c.png'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Чем платим за дешевизну? Разговор с владельцем магазинов низких цен', 'item_pubdate': '2022-06-30 10:00:36', 'item_description': 'Когда-нибудь все вымрет, останутся только магазины низких цен как высшая форма эволюции. (Или нет.) У подобных торговых объектов быстро сформировалась преданная когорта покупателей, знатоков, корпоративных жалобщиков — которые ни на что не променяют эти магазинчики. (Или променяют, но вернутся.) Их клиенты — и пенсионеры, знающие наизусть цену гречки в каждой лавке в радиусе 20 километров, и зажиточные айтишники, не знающие ничего, кроме своего номера в очереди на апостиль. Как вообще этот мир устроен? Мы пообщались с учредителем небольшой сети — о наценках, «дорогих понтах» и конкуренции с большими сетями. Цикл публикуется при поддержке компании «ЮниСтор Групп».Читать далее…', 'item_link': 'https://money.onliner.by/2022/06/30/razgovor-s-vladelcem-magazinov-nizkix-cen', 'item_image': 'https://content.onliner.by/news/thumbnail/ca2aa749df3231e3e51b3a280720640a.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Белорусы едут в Турцию, а там инфляция выше 70%. Как выглядят цены?', 'item_pubdate': '2022-06-30 09:00:46', 'item_description': 'Если придирчиво изучать варианты отпуска, то вместо теплого моря по разным причинам может образоваться море слез: недоступный шенген, меньше прямых рейсов, неудобные стыковки. К счастью, чтобы попасть на море без визы и прямиком из Минска, есть пара вариантов, в том числе Турция. В последние месяцы оттуда приходило много новостей о космической инфляции и дешевой лире. Выгодно ли это туристам? Смотрим, что там с ценами в этом сезоне.Читать далее…', 'item_link': 'https://money.onliner.by/2022/06/30/belorusy-edut-v-turciyu-a-tam-inflyaciya-vyshe-70', 'item_image': 'https://content.onliner.by/news/thumbnail/5de26de63c9eead034789d52e8f2d75b.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Два дня без зарядки — реальность? Да! Обзор Huawei nova Y70 за 599 рублей с огромной батареей', 'item_pubdate': '2022-06-30 09:00:24', 'item_description': 'Huawei Nova Y70 — новый «бюджетник» компании, оцененный у нас в 599 рублей. Главная фишка смартфона — в объемной батарее на 6000 мАч. Что еще может предложить девайс? Ниже — подробнее о достоинствах и недостатках, а также о том, с какими устройствами он призван конкурировать.Читать далее…', 'item_link': 'https://tech.onliner.by/2022/06/30/huawei-nova-y70-review', 'item_image': 'https://content.onliner.by/news/thumbnail/f52bbae141b65cb5946f491cdf521321.jpeg'}, {'rss_url': 'https://onliner.by/feed', 'channel_title': 'Onliner', 'channel_link': 'http://www.onliner.by/', 'item_title': 'Украина. 127-й день', 'item_pubdate': '2022-06-30 08:06:46', 'item_description': 'Путин пообещал зеркальный ответ Швеции и Финляндии в случае размещения в этих странах инфраструктуры НАТО. Правительство Великобритании выделит дополнительный £1 млрд ($1,2 млрд) на оказание военной помощи Украине. Продолжаем следить за ситуацией в Украине и мире.Читать далее…', 'item_link': 'https://people.onliner.by/opinions/2022/06/30/ukraina-den-127', 'item_image': 'https://content.onliner.by/news/thumbnail/49a0ff54177ca569f1e91eecd3778d8d.jpeg'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'Yahoo News - Latest News Headlines', 'channel_link': 'https://www.yahoo.com/news', 'item_title': "Spit, 'disrespect' arrive at Wimbledon as tennis turns ugly", 'item_pubdate': '2022-06-28 22:01:51', 'item_description': 'Description not provided', 'item_link': 'https://news.yahoo.com/spit-disrespect-arrive-wimbledon-tennis-220151441.html', 'item_image': 'https://s.yimg.com/uu/api/res/1.2/Kn3F_gIJwe0a3uIOU.Tb2w--~B/aD0yMzgxO3c9MzU3MTthcHBpZD15dGFjaHlvbg--/https://media.zenfs.com/en/ap.org/4a35cff443aaabc2b49d94a5e7672369'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'Top stories - Google News', 'channel_link': 'https://news.google.com/?hl=en-US=US=US:en', 'item_title': 'Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never Faced Before’ - The New York Times', 'item_pubdate': '2022-06-30 03:02:32', 'item_description': "Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never Faced Before’The New York TimesLiz Cheney says US is 'confronting a domestic threat' in Donald TrumpCNNOpinion | Trump wanted loyalty above all. He got just the opposite.The Washington PostMSNBC’s Nicolle Wallace says Liz Cheney is targeting 'Trumpism' like her father targeted terrorism after 9/11Fox NewsRepublicans must choose Trump or the Constitution, Liz Cheney warns, describing 'threat' like no otherABC News", 'item_link': 'https://news.google.com/__i/rss/rd/articles/CBMiS2h0dHBzOi8vd3d3Lm55dGltZXMuY29tLzIwMjIvMDYvMjkvdXMvcG9saXRpY3MvbGl6LWNoZW5leS1zcGVlY2gtdHJ1bXAuaHRtbNIBAA?oc=5', 'item_image': 'image is not provided'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'NYT > World News', 'channel_link': 'https://www.nytimes.com/section/world', 'item_title': 'Vitaliy Kim, Master Motivator and Symbol of Ukraine’s Resistance', 'item_pubdate': '2022-06-30 09:00:24', 'item_description': 'Applying the lessons of taekwondo, the regional military leader has rallied the embattled southern city of Mykolaiv.', 'item_link': 'https://www.nytimes.com/2022/06/30/world/europe/ukraine-vitaliy-kim-mykolaiv.html', 'item_image': 'image is not provided'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'International: Top News And Analysis', 'channel_link': 'https://www.cnbc.com/id/100727362/device/rss/rss.html', 'item_title': "China's Xi arrives in Hong Kong in his first trip off the mainland since the onset of the pandemic", 'item_pubdate': '2022-06-30 08:48:08', 'item_description': "The trip is for the 25th anniversary on Friday of Hong Kong's handover to China from British colonial rule.", 'item_link': 'https://www.cnbc.com/2022/06/30/chinas-xi-arrives-in-hong-kong-in-first-trip-off-mainland-since-pandemic.html', 'item_image': 'image is not provided'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'World - CBSNews.com', 'channel_link': 'https://www.cbsnews.com/', 'item_title': 'U.S. to increase its military presence in Europe', 'item_pubdate': '2022-06-29 22:12:47', 'item_description': 'Amid the war in Ukraine, President Biden said Wednesday the U.S. will send more military might to nine European countries. Russia threatened to respond with "compensatory measures." Nancy Cordes has the latest from the NATO summit in Madrid.', 'item_link': 'https://www.cbsnews.com/video/us-to-increase-its-military-presence-in-europe/', 'item_image': 'https://assets2.cbsnewsstatic.com/hub/i/r/2022/06/29/4c08cced-c8b0-4cdc-be3e-10d01c731850/thumbnail/60x60/51f8a9de3eb98a1bb06411e3c6384409/cbsn-fusion-us-to-increase-its-military-presence-in-europe-thumbnail-1096498-640x360.jpg'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'NYT > Top Stories', 'channel_link': 'https://www.nytimes.com', 'item_title': 'In States Banning Abortion, a Growing Rift Over Enforcement', 'item_pubdate': '2022-06-29 21:41:55', 'item_description': 'A reluctance by some liberal district attorneys to bring criminal charges against abortion providers is already complicating the legal landscape in some states.', 'item_link': 'https://www.nytimes.com/2022/06/29/us/abortion-enforcement-prosecutors.html', 'item_image': 'https://static01.nyt.com/images/2022/06/29/us/29abortion-enforcement03/29abortion-enforcement03-moth.jpg'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'Авто Onlíner', 'channel_link': 'https://auto.onliner.by/', 'item_title': 'В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра', 'item_pubdate': '2022-06-30 11:48:45', 'item_description': 'Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.Читать далее…', 'item_link': 'https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra', 'item_image': 'https://content.onliner.by/news/thumbnail/1966c44421c57d3ec175749cde6c9e29.jpeg'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'BBC News - World', 'channel_link': 'https://www.bbc.co.uk/news/', 'item_title': 'Russia invasion: Putin still wants to take most of Ukraine - US', 'item_pubdate': '2022-06-30 03:00:59', 'item_description': "According to US intelligence assessments, Russia's invasion is likely to grind on for some time.", 'item_link': 'https://www.bbc.co.uk/news/world-europe-61990495?at_medium=RSS&at_campaign=KARANGA', 'item_image': 'image is not provided'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'BuzzFeed News', 'channel_link': 'https://www.buzzfeednews.com', 'item_title': 'She Was One Year Away From Going To College. Then The Taliban Banned Her From School.', 'item_pubdate': '2022-06-13 20:32:05', 'item_description': 'The policy prohibiting girls from attending school after sixth grade contradicts the regime’s previous promises to loosen restrictions on education rights.View Entire Post ›', 'item_link': 'https://www.buzzfeednews.com/article/syedzabiullah/afghanistan-taliban-girls-school-ban', 'item_image': 'https://img.buzzfeed.com/buzzfeed-static/static/2022-06/13/19/campaign_images/c453b771f93f/she-was-one-year-away-from-going-to-college-then--2-778-1655149050-7_dblbig.jpg'}, {'rss_url': 'https://test_url.com/xml', 'channel_title': 'Газета ВСЁ', 'channel_link': 'https://vse.sale/', 'item_title': 'Проблема перегороженных улиц', 'item_pubdate': '2022-06-28 19:52:00', 'item_description': 'Празднование Дня города прошло на высоком уровне - была составлена насыщенная программа, соблюдались меры безопасности и контроля, оперативно убран мусор.', 'item_link': 'https://vse.sale/news/view/37519', 'item_image': 'image is not provided'}] diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_1.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_1.xml new file mode 100644 index 00000000..ba8f81c6 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_1.xml @@ -0,0 +1,27 @@ + + + +Yahoo News - Latest News & Headlines +https://www.yahoo.com/news +The latest news and headlines from Yahoo! News. Get breaking news stories and in-depth coverage with videos and photos. +en-US +Copyright (c) 2022 Yahoo! Inc. All rights reserved +Thu, 30 Jun 2022 05:40:03 -0400 +5 + +Yahoo News - Latest News & Headlines +https://www.yahoo.com/news +http://l.yimg.com/rz/d/yahoo_news_en-US_s_f_p_168x21_news.png + + +Spit, 'disrespect' arrive at Wimbledon as tennis turns ugly +https://news.yahoo.com/spit-disrespect-arrive-wimbledon-tennis-220151441.html +2022-06-28T22:01:51Z +Associated Press +spit-disrespect-arrive-wimbledon-tennis-220151441.html + + + + + + diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_10.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_10.xml new file mode 100644 index 00000000..44c7b7fc --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_10.xml @@ -0,0 +1,24 @@ + + + <![CDATA[BBC News - World]]> + + https://www.bbc.co.uk/news/ + + https://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif + BBC News - World + https://www.bbc.co.uk/news/ + + RSS for Node + Thu, 30 Jun 2022 08:51:54 GMT + + + 15 + + <![CDATA[Russia invasion: Putin still wants to take most of Ukraine - US]]> + + https://www.bbc.co.uk/news/world-europe-61990495?at_medium=RSS&at_campaign=KARANGA + https://www.bbc.co.uk/news/world-europe-61990495 + Thu, 30 Jun 2022 03:00:59 GMT + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_11.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_11.xml new file mode 100644 index 00000000..2098715c --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_11.xml @@ -0,0 +1,27 @@ + + + + + RSS Generator 2.1.1 + http://www.rssboard.org/rss-specification + Газета ВСЁ + https://vse.sale/ + Лента новостей Газеты ВСЁ.Онлайн + ru-RU + + https://vse.sale/images/logo.png + Газета ВСЁ + https://vse.sale/ + 88 + 31 + Газета ВСЁ + + + Проблема перегороженных улиц + Празднование Дня города прошло на высоком уровне - была составлена насыщенная программа, соблюдались меры безопасности и контроля, оперативно убран мусор. + https://vse.sale/news/view/37519 + https://vse.sale/news/view/37519 + Tue, 28 Jun 2022 19:52:00 +0300 + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_12.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_12.xml new file mode 100644 index 00000000..35d8b363 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_12.xml @@ -0,0 +1,24 @@ + + +ru +1991-2022, АО "Коммерсантъ" +http://blogs.law.harvard.edu/tech/rss +Коммерсантъ. Лента новостей +https://www.kommersant.ru/ +Регулярно обновляемая новостная лента ИД "Коммерсантъ" +Thu, 30 Jun 2022 12:08:00 +0300 + +https://im.kommersant.ru/pics/yatlogo.gif +ИД "Коммерсантъ" +https://www.kommersant.ru/ + + +https://www.kommersant.ru/doc/5436427 +Общество +В Приангарье объявила о закрытии одна из старейших в регионе газета «Время» +https://www.kommersant.ru/doc/5436427 +Thu, 30 Jun 2022 12:03:00 +0300 +Коллектив независимой газеты «Время», издаваемой в Ангарске Иркутской области с 1951 года, объявил о закрытии издания из-за отсутствия средств на его выпуск. Как сообщила в авторской колонке редактор газеты Галина Амяга, это произошло из-за сокращения денежного потока со стороны подписчиков и рекламодателей.«Газету делали за счет подписки и рекламы. То есть за счет ее читателей и рекламодателей. Сейчас нет денег ни у тех, ни у других. Одни экономят на подписке, другие — на рекламе. А денег надо много. Подняла цены типография, выросла стоимость бумаги, подорожал бензин, увеличились налоги и минимальная оплата труда. Издание народной газеты стало не по карману. Нам пришлось отказаться от субботнего выпуска, уменьшить число страниц в четверговом выпуске, сократить число телепрограмм, так как подписка на них для газеты тоже была платной»,— сообщила Галина Амяга.Газета «Время» до момента экономических сложностей издавалась дважды в неделю — по четвергам и субботам. Заявленный подписной тираж составлял 10 тыс… + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_2.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_2.xml new file mode 100644 index 00000000..86fd4e79 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_2.xml @@ -0,0 +1,20 @@ + + +NFE/5.0 +Top stories - Google News +https://news.google.com/?hl=en-US&gl=US&ceid=US:en +en-US +news-webmaster@google.com +2022 Google Inc. +Thu, 30 Jun 2022 09:09:24 GMT +Google News + +Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never Faced Before’ - The New York Times +https://news.google.com/__i/rss/rd/articles/CBMiS2h0dHBzOi8vd3d3Lm55dGltZXMuY29tLzIwMjIvMDYvMjkvdXMvcG9saXRpY3MvbGl6LWNoZW5leS1zcGVlY2gtdHJ1bXAuaHRtbNIBAA?oc=5 +CAIiENehslN_1KKrbIrNcALHTwwqFwgEKg8IACoHCAowjuuKAzCWrzwwloEY +Thu, 30 Jun 2022 03:02:32 GMT +
  1. Liz Cheney Calls Trump ‘a Domestic Threat That We Have Never Faced Before’  The New York Times
  2. Liz Cheney says US is 'confronting a domestic threat' in Donald Trump  CNN
  3. Opinion | Trump wanted loyalty above all. He got just the opposite.  The Washington Post
  4. MSNBC’s Nicolle Wallace says Liz Cheney is targeting 'Trumpism' like her father targeted terrorism after 9/11  Fox News
  5. Republicans must choose Trump or the Constitution, Liz Cheney warns, describing 'threat' like no other  ABC News
+The New York Times +
+
+
\ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_3.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_3.xml new file mode 100644 index 00000000..cdd05d4b --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_3.xml @@ -0,0 +1,32 @@ + + +NYT > World News +https://www.nytimes.com/section/world + + +en-us +Copyright 2022 The New York Times Company +Thu, 30 Jun 2022 09:05:35 +0000 +Thu, 30 Jun 2022 09:02:04 +0000 + +NYT > World News +https://static01.nyt.com/images/misc/NYT_logo_rss_250x40.png +https://www.nytimes.com/section/world + + +Vitaliy Kim, Master Motivator and Symbol of Ukraine’s Resistance +https://www.nytimes.com/2022/06/30/world/europe/ukraine-vitaliy-kim-mykolaiv.html +https://www.nytimes.com/2022/06/30/world/europe/ukraine-vitaliy-kim-mykolaiv.html + +Applying the lessons of taekwondo, the regional military leader has rallied the embattled southern city of Mykolaiv. +Roger Cohen +Thu, 30 Jun 2022 09:00:24 +0000 +Russian Invasion of Ukraine (2022) +Vitaliy Kim +Zelensky, Volodymyr +Putin, Vladimir V +Mykolaiv (Ukraine) +Ukraine + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_4.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_4.xml new file mode 100644 index 00000000..ee516021 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_4.xml @@ -0,0 +1,32 @@ + + + +en-us +60 +International: Top News And Analysis + +100727362 +franchise +section +https://www.cnbc.com/world-top-news/ + +Thu, 30 Jun 2022 08:40 GMT +Thu, 30 Jun 2022 08:40 GMT +https://www.cnbc.com/world-top-news/ + + + + +https://www.cnbc.com/2022/06/30/chinas-xi-arrives-in-hong-kong-in-first-trip-off-mainland-since-pandemic.html +107082955 +cnbcnewsstory +107082955 +false +China's Xi arrives in Hong Kong in his first trip off the mainland since the onset of the pandemic + + + +Thu, 30 Jun 2022 08:48:08 GMT + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_5.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_5.xml new file mode 100644 index 00000000..78e35657 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_5.xml @@ -0,0 +1,17 @@ + + +World - CBSNews.com +https://www.cbsnews.com/ +World From CBSNews.com +Thu, 30 Jun 2022 05:07:27 -0400 +5 + +U.S. to increase its military presence in Europe +https://www.cbsnews.com/video/us-to-increase-its-military-presence-in-europe/ +Amid the war in Ukraine, President Biden said Wednesday the U.S. will send more military might to nine European countries. Russia threatened to respond with "compensatory measures." Nancy Cordes has the latest from the NATO summit in Madrid. +Wed, 29 Jun 2022 22:12:47 -0400 +https://assets2.cbsnewsstatic.com/hub/i/r/2022/06/29/4c08cced-c8b0-4cdc-be3e-10d01c731850/thumbnail/60x60/51f8a9de3eb98a1bb06411e3c6384409/cbsn-fusion-us-to-increase-its-military-presence-in-europe-thumbnail-1096498-640x360.jpg +ee766b24-ca99-4e43-b3b6-7aea678751de + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_6.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_6.xml new file mode 100644 index 00000000..965c7ca9 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_6.xml @@ -0,0 +1,33 @@ + + +NYT > Top Stories +https://www.nytimes.com + + +en-us +Copyright 2022 The New York Times Company +Thu, 30 Jun 2022 09:08:53 +0000 +Thu, 30 Jun 2022 08:22:16 +0000 + +NYT > Top Stories +https://static01.nyt.com/images/misc/NYT_logo_rss_250x40.png +https://www.nytimes.com + + +In States Banning Abortion, a Growing Rift Over Enforcement +https://www.nytimes.com/2022/06/29/us/abortion-enforcement-prosecutors.html +https://www.nytimes.com/2022/06/29/us/abortion-enforcement-prosecutors.html + +A reluctance by some liberal district attorneys to bring criminal charges against abortion providers is already complicating the legal landscape in some states. +J. David Goodman and Jack Healy +Wed, 29 Jun 2022 21:41:55 +0000 +Abortion +Law and Legislation +District Attorneys +Texas + +Callaghan O'Hare/Reuters +Abortion rights protesters outside a courthouse in Houston. Some Democratic prosecutors are uneasy about declaring their districts safe havens for abortions, worried doing so could be used as grounds for their own removal by Republican leaders. + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_7.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_7.xml new file mode 100644 index 00000000..f02bdf89 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_7.xml @@ -0,0 +1,33 @@ + + +Авто Onlíner +https://auto.onliner.by/ +Авто Onlíner +Thu, 30 Jun 2022 11:48:45 +0300 +Onliner +ru + +https://content.onliner.by/pic/logo.png +181 +53 +Авто Onlíner +https://auto.onliner.by/ + + + +<![CDATA[ В Бобруйске тополь упал на машину. Не было ни грозы, ни ветра ]]> + +https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra +Thu, 30 Jun 2022 11:48:45 +0300 +Onliner + + + +https://auto.onliner.by/2022/06/30/v-bobrujske-topol-upal-na-mashinu-ne-bylo-ni-grozy-ni-vetra + +

Вчера вечером в самом центре Бобруйска на автостоянку упало дерево. В этот момент здесь стоял кроссовер Hyundai, внутри которого находилась женщина-водитель. Подробности пишет сайт Komkur.info.

Читать далее…

]]> +
+ +
+
+
\ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_8.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_8.xml new file mode 100644 index 00000000..44c7b7fc --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_8.xml @@ -0,0 +1,24 @@ + + + <![CDATA[BBC News - World]]> + + https://www.bbc.co.uk/news/ + + https://news.bbcimg.co.uk/nol/shared/img/bbc_news_120x60.gif + BBC News - World + https://www.bbc.co.uk/news/ + + RSS for Node + Thu, 30 Jun 2022 08:51:54 GMT + + + 15 + + <![CDATA[Russia invasion: Putin still wants to take most of Ukraine - US]]> + + https://www.bbc.co.uk/news/world-europe-61990495?at_medium=RSS&at_campaign=KARANGA + https://www.bbc.co.uk/news/world-europe-61990495 + Thu, 30 Jun 2022 03:00:59 GMT + + + \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_9.xml b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_9.xml new file mode 100644 index 00000000..d9fc4191 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/Tests_files/tests_xmls/rss_9.xml @@ -0,0 +1,28 @@ + + + BuzzFeed News + https://www.buzzfeednews.com + + en + Copyright 2022 BuzzFeed, Inc. + BuzzFeed, Reporting To You + Thu, 30 Jun 2022 09:02:24 +0000 + editor@buzzfeed.com (https://www.buzzfeednews.com/article/buzzfeednews/about-buzzfeed-news) + editor@buzzfeed.com (https://www.buzzfeednews.com/article/buzzfeednews/about-buzzfeed-news) + + https://webappstatic.buzzfeed.com/static/images/public/rss/logo-news.png + BuzzFeed News + https://www.buzzfeednews.com + + + She Was One Year Away From Going To College. Then The Taliban Banned Her From School. + The policy prohibiting girls from attending school after sixth grade contradicts the regime’s previous promises to loosen restrictions on education rights.


View Entire Post ›

]]>
+ https://www.buzzfeednews.com/article/syedzabiullah/afghanistan-taliban-girls-school-ban + Mon, 13 Jun 2022 20:32:05 -0400 + https://www.buzzfeednews.com/article/syedzabiullah/afghanistan-taliban-girls-school-ban + Inequality + + Syed Zabiullah Langari +
+
+
\ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/__init__.py b/Sholomitski Dmitry/rss_reader/__init__.py new file mode 100644 index 00000000..9e3b0894 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/__init__.py @@ -0,0 +1,39 @@ +import sys +import os +sys.path.append(os.path.dirname(__file__)) + + +class RSSParser: + @classmethod + def text_cleaner(cls, param): + pass + + @classmethod + def time_parser(cls, param): + pass + + @classmethod + def check_url(cls, param): + pass + + @classmethod + def parser(cls, self, param): + pass + + @classmethod + def rss_print(cls, list_of_items): + pass + + @classmethod + def json_print(cls, list_of_items): + pass + + @classmethod + def save_to_html(cls, self, param): + pass + + +class RSSarchive: + @classmethod + def getarchive(cls, param): + pass \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/__main__.py b/Sholomitski Dmitry/rss_reader/__main__.py new file mode 100644 index 00000000..c7090ce5 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/__main__.py @@ -0,0 +1,4 @@ +from rss_reader import main + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/pyproject.toml b/Sholomitski Dmitry/rss_reader/pyproject.toml new file mode 100644 index 00000000..fa7093a3 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools>=42"] +build-backend = "setuptools.build_meta" \ No newline at end of file diff --git a/Sholomitski Dmitry/rss_reader/rss_exceptions.py b/Sholomitski Dmitry/rss_reader/rss_exceptions.py new file mode 100644 index 00000000..7f2e018f --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/rss_exceptions.py @@ -0,0 +1,22 @@ +class RssReaderException(Exception): + pass + + +class DateTimeError(RssReaderException): + pass + + +class EmptyUrlError(RssReaderException): + pass + + +class BadUrlError(RssReaderException): + pass + + +class NoNewsinInCache(RssReaderException): + pass + + +class RssURLError(RssReaderException): + pass diff --git a/Sholomitski Dmitry/rss_reader/rss_reader.py b/Sholomitski Dmitry/rss_reader/rss_reader.py new file mode 100644 index 00000000..6e8f17ba --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/rss_reader.py @@ -0,0 +1,465 @@ +import html +import json +import os +import pickle +import re +import sys +from datetime import datetime +from urllib.parse import urlparse + +import requests +from bs4 import BeautifulSoup +from colorama import Fore, Style +from pygments import highlight, lexers, formatters +from dateparser import parse +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.ttfonts import TTFont +from xhtml2pdf import pisa +from xhtml2pdf.default import DEFAULT_FONT + +import rss_exceptions +from settings import logger_info, check_args + + +class RSSParser: + """ + RSSparser base class. Takes a dictionary with settings as input and outputs needed information in the required form + """ + + def __init__(self, settings): + self.settings = settings + + self.rss_content = self.url_request(settings['source']) + self.list_of_items = self.parser(self.rss_content) + self.items_for_print = sorted(self.list_of_items, key=lambda x: x['item_pubdate'], reverse=True)[ + :settings['limit']] + + if self.settings['json']: + RSSParser.json_print(self.items_for_print, self.settings['color']) + else: + RSSParser.rss_print(self.items_for_print, self.settings['color']) + + if self.settings['pdf']: + self.save_to_pdf(self.items_for_print, settings['pdf']) + if self.settings['html']: + self.save_to_html(self.items_for_print, settings['html']) + + @staticmethod + def valid_path(checked_path): + """ + funktion checks if passed into function path exists and tries to create it if it doesn't. + If path exists or is created successfully, method returns given path, + else - returns default path value for saving files. + :param path: path to check + :return: path for saving files + """ + + if os.path.exists(checked_path): + return checked_path + else: + try: + os.makedirs(checked_path) + return checked_path + + except OSError: + return os.path.dirname(__file__) + + @staticmethod + def load_to_archive(new_from_reader): + """ + Load list of news items to pickle + :param new_from_reader: list of dictionaries of news items + :return: Nothing + """ + if os.path.exists(os.getcwd() + '/.archive.pkl'): + with open(os.getcwd() + '/.archive.pkl', 'rb') as pkl: + unpickler = pickle.Unpickler(pkl) + archive = unpickler.load() + for item in new_from_reader: + if item in archive: + pass + else: + archive.append(item) + + else: + archive = new_from_reader + + with open(os.getcwd() + '/.archive.pkl', 'wb') as pkl: + pickle.dump(archive, pkl) + + @staticmethod + def print_to_text_format(dict_for_print: dict, color): + """ + Print all the attributes of a news item + :param dict_for_print: Dictionary of news attributes + :return: print parametres + """ + if color: + + print(Fore.RED, f"Title: {dict_for_print['item_title']}") + print(Fore.LIGHTWHITE_EX, f"Description: {dict_for_print['item_description']}") + print(Fore.MAGENTA, f"Published: {dict_for_print['item_pubdate']}") + print(Fore.YELLOW, f"Image: {dict_for_print['item_image']}") + print(Fore.LIGHTBLUE_EX, f"Read more: {dict_for_print['item_link']}",Style.RESET_ALL) + else: + print(f"Title: {dict_for_print['item_title']}") + print(f"Description: {dict_for_print['item_description']}") + print(f"Published: {dict_for_print['item_pubdate']}") + print(f"Image: {dict_for_print['item_image']}") + print(f"Read more: {dict_for_print['item_link']}") + + @staticmethod + def time_parser(date): + """ + Takes the date and returns it in the single format + + :param date: date in any format + :return: date in format '%Y-%m-%d %H:%M:%S' + """ + try: + converted_date = parse(date).strftime('%Y-%m-%d %H:%M:%S') + return converted_date + + except AttributeError: + raise rss_exceptions.DateTimeError(f'unsupported pubDate format in feed') + + @staticmethod + def check_url(url='') -> bool: + """ + :param url: url from settings + :return: True if url is valid + """ + + logger_info.info(f'Validating URL: {url}') + + if url is None: + raise rss_exceptions.EmptyUrlError('Empty argument passed, please add an URL to proceed') + url = url.strip() + result = urlparse(url) + if all([result.netloc, result.scheme]): + logger_info.info('URL validated successfully') + return True + else: + raise rss_exceptions.BadUrlError( + 'Invalid URL: URL must contain scheme and network location, try to add https://') + + @staticmethod + def text_cleaner(string): + """ + Clears the string of unnecessary characters + + :param string: virgin string + :return: clean string + """ + string = re.sub('<[^<]+>', '', html.unescape(string)) + string = re.sub('\xa0', ' ', string).strip() + return string + + def url_request(self, url): + """ + + :param url: link to rss source + :return: content of url in string format + """ + headers_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' + 'Chrome/102.0.5005.62 Safari/537.36', + 'Accept': 'text/html,application/xhtml+xml,application/xml;' + 'q=0.9,image/avif,image/webp,image/apng,*/*;' + 'q=0.8,application/signed-exchange;v=b3;q=0.9', + } + + logger_info.info(f'Making a request to {url} ') + if RSSParser.check_url(url): + try: + with requests.get(url, headers=headers_dict, timeout=2) as response: + logger_info.info('Connecting to URL') + if response.status_code == 200: + logger_info.info('Successfully connected to URL, reading data') + + rss_content = response.content + except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout): + print('Bad URL, cann\'t connect') + sys.exit() + + logger_info.info('Rss data successfully decoded') + + return rss_content + + def parser(self, rss_content): + """ + Parses the received information of each news item and saves it in the archive + :param rss_content: content of rss in string format + :return: list of dictionary with next parametres: 'rss_url','channel_title','channel_link','item_title', + 'item_pubdate','item_description','item_link','item_image' + """ + + list_of_items = [] + logger_info.info(f'Fetching RSS') + soup = BeautifulSoup(rss_content, 'xml') + + if soup.find_all('item') == []: + raise rss_exceptions.RssURLError('Incorrect ULR, cann\'t fetch RSS. Probably it\'s HTML link') + + channel_title = soup.find("title").text + + if soup.find('link').text != '': + channel_link = soup.find('link').text + elif soup.find('atom:link').get('href') != '': + channel_link = soup.find('atom:link').get('href') + else: + channel_link = '' + + for item in soup.find_all('item'): + + item_title = RSSParser.text_cleaner( + item.title.text) if item.title.text is not None else 'Title not provided' + item_pubdate = RSSParser.time_parser( + item.pubDate.text) if item.pubDate is not None else 'Date is not provided' + item_description = RSSParser.text_cleaner( + item.description.text) if item.description is not None else 'Description not provided' + if item_description == '': + item_description = 'Description not provided' + item_link = item.link.text if item.link is not None else 'link is not provided' + + image_template = ('media:content', 'media:thumbnail', 'enclosure', "image") + + for template in image_template: + if item.find(template) is not None: + + if item.find(template).get("url") is not None: + item_image = item.find(template).get("url") + elif item.find(template).text != '': + item_image = item.find(template).text + break + else: + item_image = 'image is not provided' + + list_of_items.append({ + 'rss_url': self.settings['source'], + 'channel_title': channel_title, + 'channel_link': channel_link, + 'item_title': item_title, + 'item_pubdate': item_pubdate, + 'item_description': item_description, + 'item_link': item_link, + 'item_image': item_image + }) + + RSSParser.load_to_archive(list_of_items) + return list_of_items + + @staticmethod + def rss_print(items_for_print, color=False): + """ + + :param items_for_print: list of news items to print + :return: print news items in stdout + """ + logger_info.info(f' printing in needed format') + + print_header = True + + for number_item in range(len(items_for_print)): + if items_for_print[number_item]['channel_title'] != items_for_print[number_item - 1]['channel_title']: + print_header = True + if print_header: + if color: + print(Fore.YELLOW, 'channel title: ', items_for_print[number_item]['channel_title']) + print(Fore.YELLOW, 'channel link: ', items_for_print[number_item]['channel_link']) + print(Fore.BLUE, '*' * 120, Style.RESET_ALL) + else: + print('channel title: ', items_for_print[number_item]['channel_title']) + print('channel link: ', items_for_print[number_item]['channel_link']) + print('*' * 120) + print_header = False + RSSParser.print_to_text_format(items_for_print[number_item], color) + print('-' * 120) + + @staticmethod + def json_print(items_for_print, color=False): + """ + :param items_for_print: list of dictionaries of news items to print + :return: print news items in stdout in json format + """ + for item in items_for_print: + json_formatted_text = json.dumps(item, indent=4, ensure_ascii=False) + if color: + colored_json = highlight(json_formatted_text, lexers.JsonLexer(), formatters.TerminalFormatter()) + print(colored_json) + else: + print(json_formatted_text) + + def save_to_html(self, items_for_print, path_to_save=''): + + """ + saves the needed news to an HTML page + :param items_for_print: items_for_print: list of dictionaries of news items + :return: save in HTML page + """ + + html_content = '\n\n\n\n' \ + 'Formatted RSS News\n\n' + + print_header = True + + for number_item in range(len(items_for_print)): + + if items_for_print[number_item]['channel_title'] != items_for_print[number_item - 1]['channel_title']: + print_header = True + + if print_header: + html_content += f"

Channel\'s title: {items_for_print[number_item]['channel_title']}

\n" + html_content += f"

Link to channel: {items_for_print[number_item]['channel_link']}

\n" + + print_header = False + html_content += '
' + if items_for_print[number_item]['item_image'] == 'image is not provided': + items_for_print[number_item]['item_image'] = 'https://user-images.githubusercontent.com/' \ + '10515204/56117400-9a911800-5f85-11e9-878b-3f998609a6c8.jpg' + + html_content += f"""\"\"\n +
+

{items_for_print[number_item]['item_title']}

\n +

{items_for_print[number_item]['item_description']}

\n +

Published at: {items_for_print[number_item]['item_pubdate']}

\n +

Read more

\n
""" + html_content += '' + if self.settings['html']: + logger_info.info('saving to HTML file') + path_to_save = RSSParser.valid_path(path_to_save) + path_to_file = os.path.join(path_to_save, "export.html") + output = open(path_to_file, "w", encoding='utf-8') + output.write(html_content) + print(f'Your result saved to {path_to_file}') + + output.close() + return html_content + + def save_to_pdf(self, items_for_print, path_to_save=''): + """ + + saves the needed news to an PDF file (with using save_to_html funktion makes html and convert to PDF file) + :param items_for_print: list of dictionaries of news items to save + :return: convert HTML to PDF + """ + # open output file for writing (truncated binary) + logger_info.info('saving to PDF file') + + path_to_save = RSSParser.valid_path(path_to_save) + path_to_file = os.path.join(path_to_save, 'export.pdf') + with open(path_to_file, "w+b") as result_file: + font_path = os.path.dirname(__file__) + r'/Fonts/calibri.ttf' + pdfmetrics.registerFont(TTFont('Calibri', font_path)) + DEFAULT_FONT["helvetica"] = "Calibri" + # convert HTML to PDF + source_html = self.save_to_html(items_for_print) + pisa_status = pisa.CreatePDF(source_html, dest=result_file, encoding='utf-8') + print(f'Your result saved to {path_to_file}') + + # return False on success and True on errors + return pisa_status.err + + +class RSSarchive(RSSParser): + """ + If the date is given, it downloads the archive, checks it with the required settings and prints it out + """ + + def __init__(self, settings): + archive_path = os.getcwd() + '/.archive.pkl' + self.settings = settings + color = settings['color'] + archive = RSSarchive.getarchive(archive_path) + + try: + settings['date'] = str(settings['date']) + datetime.strptime(settings['date'], '%Y%m%d') + + list_from_archive = RSSarchive.get_items_from_archive(archive, settings) + items_for_print = sorted(list_from_archive, key=lambda x: x['item_pubdate'])[:settings['limit']] + + if settings['json']: + RSSParser.json_print(items_for_print, color) + else: + RSSParser.rss_print(items_for_print, color) + + if self.settings['pdf']: + self.save_to_pdf(items_for_print) + if self.settings['html']: + self.save_to_html(items_for_print) + + except ValueError: + print(f'Entered date "{settings["date"]}" not in needed format, use this template:YYYYMMDD') + sys.exit() + + @staticmethod + def getarchive(archive_path): + """ + + :param archive_path: path to archive + :return: list of dictionaries with news items + """ + logger_info.info(f'Getting new from local Archive') + try: + with open(archive_path, 'rb') as pkl: + unpickler = pickle.Unpickler(pkl) + archive = unpickler.load() + + return archive + except (FileNotFoundError, TypeError): + print('There no any news in cache') + sys.exit(1) + + @staticmethod + def get_items_from_archive(archive, settings): + """ + + :param archive: list of dictionaries of news items + :param settings: required settings given by user + :return: news checked with settings + """ + logger_info.info(f'Filtering new new in archive with provided settings') + return_list = [] + for item in archive: + if item['item_pubdate'][:10].replace('-', '') == settings['date']: + if settings['source'] in (item['rss_url'], None): + return_list.append(item) + if return_list == []: + if settings['source'] is not None: + in_source = f"at {settings['source']}" + else: + in_source = '' + print(f'There no any news in cache with your date ({settings["date"]}) {in_source}') + return return_list + + +def main(): + settings = check_args() + + if settings['date'] is None: + RSSParser(settings) + + else: + RSSarchive(settings) + + +if __name__ == '__main__': + + try: + main() + except Exception as e: + print(f'Something goes wrong: {e}') + + diff --git a/Sholomitski Dmitry/rss_reader/settings.py b/Sholomitski Dmitry/rss_reader/settings.py new file mode 100644 index 00000000..e62b71b3 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/settings.py @@ -0,0 +1,45 @@ +import argparse +import logging +import os + + +def get_args(args=None): + default_path = os.path.dirname(__file__) + parser = argparse.ArgumentParser(description='RSS parser') + parser.add_argument('source', default=None, help='RSS URL', nargs='?') + parser.add_argument("--version", help="Print version info and exit", action="version", + version="You are using %(prog)s version 1.5") + parser.add_argument('--json', action='store_true', default=False, help='Save result as in JSON file') + parser.add_argument('--limit', type=int, default=None, help='Limit news if this parameter provided') + parser.add_argument('-v', '--verbose', action='store_true', default=False, help="Output verbose messages") + parser.add_argument("--colorize", help="Enables colored output mode", action="store_true", default=False) + parser.add_argument('--date', type=str, help='Gets a date in YYYYMMDD format. Print news from the specified date.') + + parser.add_argument('--to-html', nargs='?', const=f"{default_path}", action="store", + help='Convert news to HTML file (provide path to folder where save export file)') + parser.add_argument('--to-pdf', nargs='?', const=f"{default_path}", action="store", + help='Convert news to PDF file (provide path to folder where save export file)') + + return parser.parse_args(args) + + +def check_args(args=None): + args = get_args(args) + return { + 'limit': int(args.limit) if args.limit else None, + 'json': True if args.json else False, + 'verbose': logging.INFO if args.verbose else logger_info.disable(), + 'date': args.date if args.date else None, + 'pdf': args.to_pdf if args.to_pdf else False, + 'html': args.to_html if args.to_html else False, + 'source': args.source if args.source else None, + 'color':True if args.colorize else False + } + + +logger_info = logging +log_format = "%(levelname)s %(asctime)s - %(message)s" +logger_info.basicConfig(level=logging.INFO, + format=log_format, + datefmt='%d:%m:%Y %H:%M:%S', + ) diff --git a/Sholomitski Dmitry/rss_reader/test_reader.py b/Sholomitski Dmitry/rss_reader/test_reader.py new file mode 100644 index 00000000..1d0fe1a5 --- /dev/null +++ b/Sholomitski Dmitry/rss_reader/test_reader.py @@ -0,0 +1,185 @@ +from unittest import TestCase, main +from unittest.mock import patch, call + +import settings +from rss_reader import RSSParser, RSSarchive +from rss_reader import rss_exceptions + + +class TestRSSParser(TestCase): + settings = { + 'limit': 1, + 'json': False, + 'verbose': False, + 'source': 'https://test_url.com/xml', + 'date': None, + 'html': False, + 'pdf': False, + 'color': False + } + + def test_process_string(self): + """ + Tests for process_string method of RssReader class + :return: None + """ + self.assertEqual(RSSParser.text_cleaner('Suzy & John'), 'Suzy & John') + + self.assertEqual(RSSParser.text_cleaner('",>,<'), '",>,<') + self.assertEqual( + RSSParser.text_cleaner('

May 25, 2022 – In its ... shortage.

'), + 'May 25, 2022 – In its ... shortage.') + self.assertEqual( + RSSParser.text_cleaner('

May 25,\xa02022 – In its ... shortage.

'), + 'May 25, 2022 – In its ... shortage.') + + def test_pubdate(self): + """ + Tests for unify_pubdate method of RssReader class + :return: None + """ + self.assertEqual(RSSParser.time_parser('Tue, 24 May 2022 23:45:43 GMT'), '2022-05-24 23:45:43') + self.assertEqual(RSSParser.time_parser('2022-05-30T22:22:05Z'), '2022-05-30 22:22:05') + self.assertEqual(RSSParser.time_parser('Fri, 13 May 2022 17:15:00 -0400'), '2022-05-13 17:15:00') + self.assertEqual(RSSParser.time_parser('2022-06-04T01:00:00+04:00'), '2022-06-04 01:00:00') + with self.assertRaises(rss_exceptions.DateTimeError): + RSSParser.time_parser('') + + def test_validate_url(self): + """ + Tests for validate_url method of RssReader class + :return: None + """ + self.assertTrue(RSSParser.check_url('https://news.google.com/rss/')) + self.assertTrue(RSSParser.check_url('https://www.nytimes.com/section/world/rss.xml')) + with self.assertRaises(rss_exceptions.BadUrlError): + RSSParser.check_url('url') + with self.assertRaises(rss_exceptions.BadUrlError): + RSSParser.check_url('news.google.com/rss/') + with self.assertRaises(rss_exceptions.BadUrlError): + RSSParser.check_url('https://') + with self.assertRaises(rss_exceptions.EmptyUrlError): + RSSParser.check_url(None) + + def test_parse_args(self): + parser = settings.get_args(['--limit', '3', '--verbose', '--json', 'https://money.onliner.by/feed', '--to-html', + '--to-pdf']) + self.assertTrue(parser.limit) + self.assertTrue(parser.verbose) + self.assertTrue(parser.json) + self.assertTrue(parser.source) + self.assertTrue(parser.to_pdf) + self.assertTrue(parser.to_html) + + with patch('builtins.input', return_value='--version'): + self.assertRaises(SystemExit) + + with patch('builtins.input', return_value='--help'): + self.assertRaises(SystemExit) + + def test_check_args(self): + parser = settings.check_args(['--limit', '3', '--verbose', '--json', 'https://money.onliner.by/feed']) + archive_parser = settings.check_args(['--date', '20220606', '--to-html', '--to-pdf', '-v', '--path', 'source']) + self.assertEqual(parser['limit'], 3) + self.assertTrue(parser['verbose']) + self.assertTrue(archive_parser['verbose']) + self.assertEqual(parser['source'], 'https://money.onliner.by/feed') + self.assertTrue(parser['json']) + self.assertIsNone(archive_parser['source']) + self.assertEqual(archive_parser['date'], '20220606') + self.assertTrue(archive_parser['pdf']) + self.assertTrue(archive_parser['html']) + + @patch.object(RSSParser, 'url_request') + def test_parser_mock(self, mock_url_request): + files_dict = { + 'Tests_files/tests_xmls/rss_1.xml': 'Tests_files/dict_files/dict_1.txt', + 'Tests_files/tests_xmls/rss_2.xml': 'Tests_files/dict_files/dict_2.txt', + 'Tests_files/tests_xmls/rss_3.xml': 'Tests_files/dict_files/dict_3.txt', + 'Tests_files/tests_xmls/rss_4.xml': 'Tests_files/dict_files/dict_4.txt', + 'Tests_files/tests_xmls/rss_5.xml': 'Tests_files/dict_files/dict_5.txt', + 'Tests_files/tests_xmls/rss_6.xml': 'Tests_files/dict_files/dict_6.txt', + 'Tests_files/tests_xmls/rss_7.xml': 'Tests_files/dict_files/dict_7.txt', + 'Tests_files/tests_xmls/rss_8.xml': 'Tests_files/dict_files/dict_8.txt', + 'Tests_files/tests_xmls/rss_9.xml': 'Tests_files/dict_files/dict_9.txt', + 'Tests_files/tests_xmls/rss_10.xml': 'Tests_files/dict_files/dict_10.txt', + 'Tests_files/tests_xmls/rss_11.xml': 'Tests_files/dict_files/dict_11.txt', + } + + for xlm_file, res_file in files_dict.items(): + with open(xlm_file, 'r') as xlm_file1, open(res_file) as res_file1: + test1_file_rss = xlm_file1.read() + test1_file_result = eval(res_file1.read()) + mock_url_request.return_value = test1_file_rss + self.assertEqual(RSSParser.parser(self, mock_url_request()), test1_file_result) + + @patch('builtins.print') + def test_rss_print(self, mock_print): + with open('Tests_files/dict_files/dict_1.txt', 'r') as rss_file1: + list_of_items = eval(rss_file1.read()) + + RSSParser.rss_print(list_of_items) + + self.assertEqual(mock_print.mock_calls, [call('channel title: ', 'Yahoo News - Latest News Headlines'), + call('channel link: ', 'https://www.yahoo.com/news'), + call( + '*' * 120), + call( + "Title: Spit, 'disrespect' arrive at Wimbledon as tennis" + " turns ugly"), + call('Description: Description not provided'), + call('Published: 2022-06-28 22:01:51'), + call( + 'Image: https://s.yimg.com/uu/api/res/1.2/Kn3F_' + 'gIJwe0a3uIOU.Tb2w--~B/aD0yMzgxO3c9MzU3MTthcHBpZD15dGFjaHlvbg' + '--/https://media.zenfs.com/en/ap.org/4a35cff443aaabc2b49d94a' + '5e7672369'), + call( + 'Read more: https://news.yahoo.com/spit-disrespect-arrive-' + 'wimbledon-tennis-220151441.html'), + call( + '-' * 120) + ]) + + @patch('builtins.print') + def test_json_print(self, mock_print): + with open('Tests_files/dict_files/dict_1.txt', 'r') as rss_file1: + list_of_items = eval(rss_file1.read()) + + RSSParser.json_print(list_of_items) + + self.assertEqual(mock_print.mock_calls, + [call('{\n "channel_link": "https://www.yahoo.com/news",' + '\n "channel_title": "Yahoo News - Latest News Headlines",' + '\n "item_description": "Description not provided",' + '\n "item_image": "https://s.yimg.com/uu/api/res/1.2/Kn3F_gIJwe0a3uIOU.Tb2w--~B' + '/aD0yMzgxO3c9MzU3MTthcHBpZD15dGFjaHlvbg--/' + 'https://media.zenfs.com/en/ap.org/4a35cff443aaabc2b49d94a5e7672369",' + '\n "item_link": "https://news.yahoo.com/spit-disrespect-arrive-wimbledon-tennis-' + '220151441.html",\n "item_pubdate": "2022-06-28 22:01:51",' + '\n "item_title": "Spit, \'disrespect\' arrive at Wimbledon as' + ' tennis turns ugly",\n "rss_url": "https://test_url.com/xml"\n}')]) + + def test_save_to_html(self): + with open('Tests_files/dict_for_print.txt') as dict_1, open('Tests_files/html_file.html') as res_file1: + html_content = RSSParser.save_to_html(self, eval(dict_1.read()), None) + + self.assertEqual(html_content, res_file1.read()) + + +class TestRSSArchive(TestCase): + + def test_getarchive(self): + with self.assertRaises(SystemExit): + RSSarchive.getarchive('url') + + with open('Tests_files/test_archive_dict.txt') as dict_file: + dict_result = eval(dict_file.read()) + self.assertEqual(RSSarchive.getarchive('Tests_files/.test_archive.pkl'), dict_result) + + def test_get_items_from_archive(self): + pass + + +if __name__ == '__main__': + main() diff --git a/Sholomitski Dmitry/rss_reader/version.py b/Sholomitski Dmitry/rss_reader/version.py new file mode 100644 index 00000000..e69de29b diff --git a/Sholomitski Dmitry/setup.py b/Sholomitski Dmitry/setup.py new file mode 100644 index 00000000..eb69573d --- /dev/null +++ b/Sholomitski Dmitry/setup.py @@ -0,0 +1,25 @@ +from setuptools import setup, find_packages +with open("requirements.txt", encoding="utf-8") as file: + requirements = file.read() + + +setup( + name='rss_reader', + version='1.5', + author='Dmitry Sholomitski', + author_email='xaos613@gmail.com', + description='RSS parser', + py_modules=["rss_reader"], + long_description='RSS parser using Python v3.10', + packages=find_packages(), + package_data={ + '': ['*.ttf'], + }, + + install_requires=requirements, + classifiers=[ + "Programming Language :: Python :: 3.10", + "Operating System :: OS Independent", + ], + entry_points={"console_scripts": ["rss_reader=rss_reader.rss_reader:main"]} +)