From ece0febbe87cd8c25163d7968ccdd396154b9474 Mon Sep 17 00:00:00 2001 From: kotartemiy Date: Wed, 1 Jul 2020 13:05:08 +0300 Subject: [PATCH] v1 for Maxim --- README.md | 488 +++++++++++++++++++++++++++++++++++++++ poetry.lock | 228 ++++++++++++++++++ pygooglenews/__init__.py | 153 ++++++++++++ pyproject.toml | 23 ++ 4 files changed, 892 insertions(+) create mode 100644 poetry.lock create mode 100644 pygooglenews/__init__.py create mode 100644 pyproject.toml diff --git a/README.md b/README.md index 176ce6d..1da70d0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,490 @@ # pygooglenews If Google News had a Python library + + +Created by Artem from [newscatcherapi.com](newscatcherapi.com) but you do not need anything from us or from anyone else to get the software going, it just works out of the box. +## Demo + +### Table of Contents +- [About](#about) +- [Examples of Use Cases](#usecase) +- [Working with Google News in Production](#production) +- [Motivation](#motivation) +- [Installation](#installation) +- [Quickstart](#quickstart) +- [Documentation](#documentation) +- [Advanced Query Search Examples](#examples) +- [About me](#aboutme) + + + +## **About** + +A python wrapper of the Google News RSS feed. + +Top stories, topic related news feeds, geolocation news feed, and an extensive full text search feed. + +This work is more of a collection of all things I could find out about how Google News functions. + +### **How is it different from other Pythonic Google News libraries?** + +1. URL-escaping user input helper for the search function +2. Extensive support for the search function that makes it simple to use: + - exact match + - in title match, in url match, etc + - search by date range (`from_` & `to_`), latest published (`when`) +3. Parsing of the sub articles. Almost always, all feeds except the search one contain a subset of similar news for each article in a feed. This package takes care of extracting those sub articles. This feature might be highly useful to ML task when you need to collect a data of similar article headlines + + + +## Examples of Use Cases + +1. Integrating a news feed to your platform/application/website +2. Collecting data by topic to train your own ML model +3. Search for latest mentions for your new product +4. Media monitoring of people/organizations — PR + + + + +## Working with Google News in Production + +Before we start, if you want to integrate Google News data to your production then I would advise you to use one of the 3 methods described above. Why? Because you do not want your servers IP address to be locked by Google. **Don't get me wrong, this Python package still works out of the box.** + +1. NewsCatcher's Google News API — all code is written for you, clean & structured JSON output. Low price. You can test it yourself with no credit card +2. [ScrapingBee API](https://www.scrapingbee.com?fpr=artem26) which handles proxy rotation for you. Each function in this package has `scraping_bee` parameter where you paste your API key. You can also try it for free, no credit card required. See [example](#scrapingbeeexample) +3. Your own proxy — already have a pool of proxies? Each function in this package has `proxies` parameter (python dictionary) where you just paste your own proxies. + + + +## **Motivation** + +I love working with the news data. I love it so much that I created [my own company that crawls for hundreds of thousands of news articles, and allow you to search it via a news API](https://newscatcherapi.com/). But this time, I want to share with the community a Python package that makes it simple to get the news data from the best search engine ever created - [Google](https://news.google.com/). + +Most likely, you know already that Google has its own [news service](https://news.google.com/). It is different from the usual Google search that we use on a daily basis (sorry [DuckDuckGo](https://duckduckgo.com/), maybe next time). + +**This package uses the RSS feed of the Google News. The [top stories page](https://news.google.com/rss), for example.** + +RSS is an XML page that is already well structured. I heavily rely on Feedparser package to parse the RSS feed. + +Google News used to have an API but it was deprecated many years ago. (Unofficial) information +about RSS syntax is decentralized over the web. There is no official documentation. So, I tried my best +to collect all this informaion in one place. + + + + +## **Installation** + +```shell script +$ pip install pygooglenews + +``` + + + +## **Quickstart** + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() + +``` + +### **Top Stories** + +```python +top = gn.top_news() +``` + +### **Stories by Topic** + +```python +business = gn.topic_headlines('business') + +``` + +### **Geolocation Specific Stories** + +```python +headquaters = gn.geo_headlines('San Fran') + +``` + +### **Stories by a Query Search** + +```python +# search for the best matching articles that mention MSFT and +# do not mention AAPL (over the past 6 month +search = gn.search('MSFT -APPL', when = '6m') + +``` + +--- + + +## **Documentation - Functions & Classes** + +### **GoogleNews Class** + +```python +from pygooglenews import GoogleNews +# default GoogleNews instance +gn = GoogleNews(lang = 'en', country = 'US') + +``` + +To get the access to all the functions, you first have to initiate the `GoogleNews` class. + +It has 2 required variables: `lang` and `country` + +You can try any combination of those 2, however, it does not exist for all. Only the combinations that are supported by GoogleNews will work. Check the official Google News page to check what is covered: + +On the bottom left side of the Google News page you may find a `Language & region` section where you can find all of the supported combinations. + + +For example, for `country=UA` (Ukraine), there are 2 languages supported: + +- `lang=uk` Ukrainian +- `lang=ru` Russian + +--- + +### **Top Stories** + +```python +top = gn.top_news(proxies=None, scraping_bee = None) + +``` + +`top_news()` returns the top stories for the selected country and language that are defined in `GoogleNews` class. The returned object contains `feed` (FeedParserDict) and `entries` list of articles found with all data parsed. + +--- + +### **Stories by Topic** + +```python +business = gn.topic_headlines('BUSINESS', proxies=None, scraping_bee = None) + +``` + +The returned object contains `feed` (FeedParserDict) and `entries` list of articles found with all data parsed. + +Accepted topics are: + +- `WORLD` +- `NATION` +- `BUSINESS` +- `TECHNOLOGY` +- `ENTERTAINMENT` +- `SCIENCE` +- `SPORTS` +- `HEALTH` + +However, you can find some other topics that are also supported by Google News. + +For example, if you search for `corona` in the search tab of `en` + `US` you will find `COVID-19` as a topic. + +The URL looks like this: `https://news.google.com/topics/CAAqIggKIhxDQkFTRHdvSkwyMHZNREZqY0hsNUVnSmxiaWdBUAE?hl=en-US&gl=US&ceid=US%3Aen` + +We have to copy the text after `topics/` and before `?`, then you can use it as an input for the `top_news()` function. + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() +covid = gn.topic_headlines('CAAqIggKIhxDQkFTRHdvSkwyMHZNREZqY0hsNUVnSmxiaWdBUAE') + +``` + +**However, be aware that this topic will be unique for each language/country combination.** + +--- + +### **Stories by Geolocation** + +```python +gn = GoogleNews('uk', 'UA') +kyiv = gn.geo_headlines('kyiv', proxies=None, scraping_bee = None) +# or +kyiv = gn.geo_headlines('kiev', proxies=None, scraping_bee = None) +# or +kyiv = gn.geo_headlines('киев', proxies=None, scraping_bee = None) +# or +kyiv = gn.geo_headlines('Київ', proxies=None, scraping_bee = None) + +``` + +The returned object contains `feed` (FeedParserDict) and `entries` list of articles found with all data parsed. + +All of the above variations will return the same feed of the latest news about Kyiv, Ukraine: + +```python +geo['feed'].title + +# 'Київ - Останні - Google Новини' + +``` + +It is language agnostic, however, it does not guarantee that the feed for any specific place will exist. For example, if you want to find the feed on `LA` or `Los Angeles` you can do it with `GoogleNews('en', 'US')`. + +The main (`en`, `US`) Google News client will most likely find the feed about the most places. + +--- + +### **Stories by a Query** + +```python +gn.search(query: str, helper = True, when = None, from_ = None, to_ = None, proxies=None, scraping_bee=None) + +``` + +The returned object contains `feed` (FeedParserDict) and `entries` list of articles found with all data parsed. + +Google News search itself is a complex function that has inherited some features from the standard Google Search. + +[The official reference on what could be inserted](https://developers.google.com/custom-search/docs/xml_results) + +The biggest obstacle that you might have is to write the URL-escaping input. To ease this process, `helper = True` is turned on by default. + +`helper` uses `urllib.parse.quote_plus` to automatically convert the input. + +For example: + +- `'New York metro opening'` --> `'New+York+metro+opening'` +- `'AAPL -MSFT'` --> `'AAPL+-MSFT'` +- `'"Tokyo Olimpics date changes"'` --> `'%22Tokyo+Olimpics+date+changes%22'` + +You can turn it off and write your own query in case you need it by `helper = False` + +`when` parameter (`str`) sets the time range for the published datetime. I could not find any documentation regarding this option, but here is what I deducted: + +- `h` for hours.(For me, worked for up to `101h`). `when=12h` will search for only the articles matching the `search` criteri and published for the last 12 hours +- `d` for days +- `m` for month (For me, worked for up to `48m`) + +I did not set any hard limit here. You may try put here anything. Probably, it will work. However, I would like to warn you that wrong inputs will not lead to an error. Instead, the `when` parameter will be ignored by the Google. + +`from_` and `to_` accept the following format of date: `%Y-%m-%d` For example, `2020-07-01` + +--- + +**[Google's Special Query Terms](https://developers.google.com/custom-search/docs/xml_results#special-query-terms) Cheat Sheet** + +Many Google's Special Query Terms have been tested one by one. Most of the core ones have been inherited by Google News service. At first, I wanted to integrate all of those as the `search()` function parameters. But, I realised that it might be a bit confusing and difficult to make them all work correctly. + +Instead, **I decided to write some kind of a cheat sheet that should give you a decent understanding of what you could do**. + +* Boolean OR Search [ OR ] + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() + +s = gn.search('boeing OR airbus') + +print(s['feed'].title) +# "boeing OR airbus" - Google News + +``` + +* Exclude Query Term [-] + +"The exclude (`-`) query term restricts results for a particular search request to documents that do not contain a particular word or phrase. To use the exclude query term, you would preface the word or phrase to be excluded from the matching documents with "-" (a minus sign)." + +* Include Query Term [+] + +"The include (`+`) query term specifies that a word or phrase must occur in all documents included in the search results. To use the include query term, you would preface the word or phrase that must be included in all search results with "+" (a plus sign). + +The URL-escaped version of **`+`** (a plus sign) is `%2B`." + +**ALWAYS USE IT IN A URL-ESCAPED VERSION WHICH IS %2B (not +)** + +* Phrase Search + +"The phrase search (`"`) query term allows you to search for complete phrases by enclosing the phrases in quotation marks or by connecting them with hyphens. + +The URL-escaped version of **`"`** (a quotation mark) is **`%22`**. + +Phrase searches are particularly useful if you are searching for famous quotes or proper names." + +* allintext + +"The **`allintext:`** query term requires each document in the search results to contain all of the words in the search query in the body of the document. The query should be formatted as **`allintext:`** followed by the words in your search query. + +If your search query includes the **`allintext:`** query term, Google will only check the body text of documents for the words in your search query, ignoring links in those documents, document titles and document URLs." + +* intitle + +"The `intitle:` query term restricts search results to documents that contain a particular word in the document title. The search query should be formatted as `intitle:WORD` with no space between the intitle: query term and the following word." + +* allintitle + +"The **`allintitle:`** query term restricts search results to documents that contain all of the query words in the document title. To use the **`allintitle:`** query term, include "allintitle:" at the start of your search query. + +Note: Putting **`allintitle:`** at the beginning of a search query is equivalent to putting [intitle:](https://developers.google.com/custom-search/docs/xml_results#TitleSearchqt) in front of each word in the search query." + +* inurl + +"The `inurl:` query term restricts search results to documents that contain a particular word in the document URL. The search query should be formatted as `inurl:WORD` with no space between the inurl: query term and the following word" + +* allinurl + +The `allinurl:` query term restricts search results to documents that contain all of the query words in the document URL. To use the `allinurl:` query term, include allinurl: at the start of your search query. + + +### List of operators that do not work (for me, at least): + +1. Most (probably all) of the `as_*` terms do not work for Google News +2. `allinlinks:` +3. `related:` + + +**Tip**. If you want to build a near real-time feed for a specific topic, use `when='1h'`. If Google captured less than 100 articles over the past hour, you should be able to retrieve all of them. + +Check the [Useful Links](notion://www.notion.so/Google-News-API-Documentation-b95117b9ecd94076bb1d8cf7c2957d78#useful-links) section if you want to dig into how Google Search works. + +Especially, [Special Query Terms](https://developers.google.com/custom-search/docs/xml_results#special-query-terms) section of Google XML reference. + +Plus, I will provide some more examples under the [Full-Text Search Examples](notion://www.notion.so/Google-News-API-Documentation-b95117b9ecd94076bb1d8cf7c2957d78#examples) section + +--- + +### **Output Body** + +All 4 functions return the `dictionary` that has 2 sub-objects: + +- `feed` - contains the information on the feed metadata +- `entries` - contains the parsed articles + +Both are inherited from the [Feedparser](https://github.com/kurtmckee/feedparser). The only change is that each dictionary under `entries` also contains `sub_articles` which are the similar articles found in the description. Usually, it is non-empty for `top_news()` and `topic_headlines()` feeds. + +**Tip** To check what is the found feed's name just check the `title` under the `feed` dictionary + +--- + + +## How to use pygooglenews with [ScrapingBee](https://www.scrapingbee.com?fpr=artem26) + +Every function has `scrapingbee` parameter. It accepts your [ScrapingBee](https://www.scrapingbee.com?fpr=artem26) API key that will be used to get the response from Google's servers. + +You can take a look at what exactly is happening in the source code: check for `__scaping_bee_request()` function under GoogleNews class + +Pay attention to the concurrency of each plan at [ScrapingBee](https://www.scrapingbee.com?fpr=artem26) + +How to use example: + +```python +gn = GoogleNews() + +# it's a fake API key, do not try to use it +gn.top_news(scraping_bee = 'I5SYNPRFZI41WHVQWWUT0GNXFMO104343E7CXFIISR01E2V8ETSMXMJFK1XNKM7FDEEPUPRM0FYAHFF5') +``` + +--- + +## How to use pygooglenews with proxies + +So, if you have your own HTTP/HTTPS proxy(s) that you want to use to make requests to Google, that's how you do it: + +```python +gn = GoogleNews() + +gn.top_news(proxies = {'https':'34.91.135.38:80'}) +``` + +--- + + +## **Advanced Querying Search Examples** + +### **Example 1. Search for artiles that mention `boeing` and do not mention `airbus`** + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() + +s = gn.search('boeing -airbus') + +print(s['feed'].title) +# "boeing -airbus" - Google News + +``` + +### **Example 2. Search for articles that mention `boeing` in title** + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() + +s = gn.search('intitle:boeing') + +print(s['feed'].title) +# "intitle:boeing" - Google News + +``` + +### **Example 3. Search for artiles that mention `boeing` in title and got published over the past hour** + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() + +s = gn.search('intitle:boeing', when = '1h') + +print(s['feed'].title) +# "intitle:boeing when:1h" - Google News + +``` + +### **Example 4. Search for artiles that mention `boeing` or `airbus`** + +```python +from pygooglenews import GoogleNews + +gn = GoogleNews() + +s = gn.search('boeing OR airbus', when = '1h') + +print(s['feed'].title) +# "boeing AND airbus when:1h" - Google News + +``` + +--- + + +## **Useful Links** + +[Stack Overflow tread from which it all began](https://stackoverflow.com/questions/51537063/url-format-for-google-news-rss-feed) + +[Google XML reference for the search query](https://developers.google.com/custom-search/docs/xml_results) + +[Google News Search parameters (The Missing Manual)](http://web.archive.org/web/20150204025359/http://blog.slashpoundbang.com/post/12975232033/google-news-search-parameters-the-missing-manual) + +--- + + +## **Built With** + +[Feedparser](https://github.com/kurtmckee/feedparser) + +[Beutifulsoup4](https://pypi.org/project/beautifulsoup4/) + +--- + + +## **About me** + +My name is Artem. I ❤️ working with news data. I am a co-founder of [NewsCatcherAPI](https://newscatcherapi.com/) + +If you are interested in hiring me, please, contact me by email - **bugara.artem@gmail.com** or **artem@newscatcherapi.com** + +Follow me on 🖋 [Twitter](https://twitter.com/bugaralife) - I write about data engineering, python, entrepreneurship, and memes. + +Want to read about how it all was done? Subscribe to [CODARIUM](https://codarium.substack.com/) \ No newline at end of file diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 0000000..598467c --- /dev/null +++ b/poetry.lock @@ -0,0 +1,228 @@ +[[package]] +category = "main" +description = "Screen-scraping library" +name = "beautifulsoup4" +optional = false +python-versions = "*" +version = "4.9.1" + +[package.dependencies] +soupsieve = [">1.2", "<2.0"] + +[package.extras] +html5lib = ["html5lib"] +lxml = ["lxml"] + +[[package]] +category = "main" +description = "Python package for providing Mozilla's CA Bundle." +name = "certifi" +optional = false +python-versions = "*" +version = "2020.6.20" + +[[package]] +category = "main" +description = "Universal encoding detector for Python 2 and 3" +name = "chardet" +optional = false +python-versions = "*" +version = "3.0.4" + +[[package]] +category = "main" +description = "Date parsing library designed to parse dates from HTML pages" +name = "dateparser" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +version = "0.7.6" + +[package.dependencies] +python-dateutil = "*" +pytz = "*" +regex = "!=2019.02.19" +tzlocal = "*" + +[[package]] +category = "main" +description = "Universal feed parser, handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds" +name = "feedparser" +optional = false +python-versions = "*" +version = "5.2.1" + +[[package]] +category = "main" +description = "Internationalized Domain Names in Applications (IDNA)" +name = "idna" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +version = "2.10" + +[[package]] +category = "main" +description = "Extensions to the standard Python datetime module" +name = "python-dateutil" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" +version = "2.8.1" + +[package.dependencies] +six = ">=1.5" + +[[package]] +category = "main" +description = "World timezone definitions, modern and historical" +name = "pytz" +optional = false +python-versions = "*" +version = "2020.1" + +[[package]] +category = "main" +description = "Alternative regular expression module, to replace re." +name = "regex" +optional = false +python-versions = "*" +version = "2020.6.8" + +[[package]] +category = "main" +description = "Python HTTP for Humans." +name = "requests" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +version = "2.24.0" + +[package.dependencies] +certifi = ">=2017.4.17" +chardet = ">=3.0.2,<4" +idna = ">=2.5,<3" +urllib3 = ">=1.21.1,<1.25.0 || >1.25.0,<1.25.1 || >1.25.1,<1.26" + +[package.extras] +security = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)"] +socks = ["PySocks (>=1.5.6,<1.5.7 || >1.5.7)", "win-inet-pton"] + +[[package]] +category = "main" +description = "Python 2 and 3 compatibility utilities" +name = "six" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" +version = "1.15.0" + +[[package]] +category = "main" +description = "A modern CSS selector implementation for Beautiful Soup." +name = "soupsieve" +optional = false +python-versions = "*" +version = "1.9.6" + +[[package]] +category = "main" +description = "tzinfo object for the local timezone" +name = "tzlocal" +optional = false +python-versions = "*" +version = "2.1" + +[package.dependencies] +pytz = "*" + +[[package]] +category = "main" +description = "HTTP library with thread-safe connection pooling, file post, and more." +name = "urllib3" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4" +version = "1.25.9" + +[package.extras] +brotli = ["brotlipy (>=0.6.0)"] +secure = ["certifi", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "pyOpenSSL (>=0.14)", "ipaddress"] +socks = ["PySocks (>=1.5.6,<1.5.7 || >1.5.7,<2.0)"] + +[metadata] +content-hash = "a880561af07a0c9832b5706a41279985738aed80ce83d1edbb4347ed42147ee6" +python-versions = "^3.6" + +[metadata.files] +beautifulsoup4 = [ + {file = "beautifulsoup4-4.9.1-py2-none-any.whl", hash = "sha256:e718f2342e2e099b640a34ab782407b7b676f47ee272d6739e60b8ea23829f2c"}, + {file = "beautifulsoup4-4.9.1-py3-none-any.whl", hash = "sha256:a6237df3c32ccfaee4fd201c8f5f9d9df619b93121d01353a64a73ce8c6ef9a8"}, + {file = "beautifulsoup4-4.9.1.tar.gz", hash = "sha256:73cc4d115b96f79c7d77c1c7f7a0a8d4c57860d1041df407dd1aae7f07a77fd7"}, +] +certifi = [ + {file = "certifi-2020.6.20-py2.py3-none-any.whl", hash = "sha256:8fc0819f1f30ba15bdb34cceffb9ef04d99f420f68eb75d901e9560b8749fc41"}, + {file = "certifi-2020.6.20.tar.gz", hash = "sha256:5930595817496dd21bb8dc35dad090f1c2cd0adfaf21204bf6732ca5d8ee34d3"}, +] +chardet = [ + {file = "chardet-3.0.4-py2.py3-none-any.whl", hash = "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"}, + {file = "chardet-3.0.4.tar.gz", hash = "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae"}, +] +dateparser = [ + {file = "dateparser-0.7.6-py2.py3-none-any.whl", hash = "sha256:7552c994f893b5cb8fcf103b4cd2ff7f57aab9bfd2619fdf0cf571c0740fd90b"}, + {file = "dateparser-0.7.6.tar.gz", hash = "sha256:e875efd8c57c85c2d02b238239878db59ff1971f5a823457fcc69e493bf6ebfa"}, +] +feedparser = [ + {file = "feedparser-5.2.1.tar.bz2", hash = "sha256:ce875495c90ebd74b179855449040003a1beb40cd13d5f037a0654251e260b02"}, + {file = "feedparser-5.2.1.tar.gz", hash = "sha256:bd030652c2d08532c034c27fcd7c85868e7fa3cb2b17f230a44a6bbc92519bf9"}, + {file = "feedparser-5.2.1.zip", hash = "sha256:cd2485472e41471632ed3029d44033ee420ad0b57111db95c240c9160a85831c"}, +] +idna = [ + {file = "idna-2.10-py2.py3-none-any.whl", hash = "sha256:b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0"}, + {file = "idna-2.10.tar.gz", hash = "sha256:b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6"}, +] +python-dateutil = [ + {file = "python-dateutil-2.8.1.tar.gz", hash = "sha256:73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c"}, + {file = "python_dateutil-2.8.1-py2.py3-none-any.whl", hash = "sha256:75bb3f31ea686f1197762692a9ee6a7550b59fc6ca3a1f4b5d7e32fb98e2da2a"}, +] +pytz = [ + {file = "pytz-2020.1-py2.py3-none-any.whl", hash = "sha256:a494d53b6d39c3c6e44c3bec237336e14305e4f29bbf800b599253057fbb79ed"}, + {file = "pytz-2020.1.tar.gz", hash = "sha256:c35965d010ce31b23eeb663ed3cc8c906275d6be1a34393a1d73a41febf4a048"}, +] +regex = [ + {file = "regex-2020.6.8-cp27-cp27m-win32.whl", hash = "sha256:fbff901c54c22425a5b809b914a3bfaf4b9570eee0e5ce8186ac71eb2025191c"}, + {file = "regex-2020.6.8-cp27-cp27m-win_amd64.whl", hash = "sha256:112e34adf95e45158c597feea65d06a8124898bdeac975c9087fe71b572bd938"}, + {file = "regex-2020.6.8-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:92d8a043a4241a710c1cf7593f5577fbb832cf6c3a00ff3fc1ff2052aff5dd89"}, + {file = "regex-2020.6.8-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:bae83f2a56ab30d5353b47f9b2a33e4aac4de9401fb582b55c42b132a8ac3868"}, + {file = "regex-2020.6.8-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:b2ba0f78b3ef375114856cbdaa30559914d081c416b431f2437f83ce4f8b7f2f"}, + {file = "regex-2020.6.8-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:95fa7726d073c87141f7bbfb04c284901f8328e2d430eeb71b8ffdd5742a5ded"}, + {file = "regex-2020.6.8-cp36-cp36m-win32.whl", hash = "sha256:e3cdc9423808f7e1bb9c2e0bdb1c9dc37b0607b30d646ff6faf0d4e41ee8fee3"}, + {file = "regex-2020.6.8-cp36-cp36m-win_amd64.whl", hash = "sha256:c78e66a922de1c95a208e4ec02e2e5cf0bb83a36ceececc10a72841e53fbf2bd"}, + {file = "regex-2020.6.8-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:08997a37b221a3e27d68ffb601e45abfb0093d39ee770e4257bd2f5115e8cb0a"}, + {file = "regex-2020.6.8-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:2f6f211633ee8d3f7706953e9d3edc7ce63a1d6aad0be5dcee1ece127eea13ae"}, + {file = "regex-2020.6.8-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:55b4c25cbb3b29f8d5e63aeed27b49fa0f8476b0d4e1b3171d85db891938cc3a"}, + {file = "regex-2020.6.8-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:89cda1a5d3e33ec9e231ece7307afc101b5217523d55ef4dc7fb2abd6de71ba3"}, + {file = "regex-2020.6.8-cp37-cp37m-win32.whl", hash = "sha256:690f858d9a94d903cf5cada62ce069b5d93b313d7d05456dbcd99420856562d9"}, + {file = "regex-2020.6.8-cp37-cp37m-win_amd64.whl", hash = "sha256:1700419d8a18c26ff396b3b06ace315b5f2a6e780dad387e4c48717a12a22c29"}, + {file = "regex-2020.6.8-cp38-cp38-manylinux1_i686.whl", hash = "sha256:654cb773b2792e50151f0e22be0f2b6e1c3a04c5328ff1d9d59c0398d37ef610"}, + {file = "regex-2020.6.8-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:52e1b4bef02f4040b2fd547357a170fc1146e60ab310cdbdd098db86e929b387"}, + {file = "regex-2020.6.8-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:cf59bbf282b627130f5ba68b7fa3abdb96372b24b66bdf72a4920e8153fc7910"}, + {file = "regex-2020.6.8-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:5aaa5928b039ae440d775acea11d01e42ff26e1561c0ffcd3d805750973c6baf"}, + {file = "regex-2020.6.8-cp38-cp38-win32.whl", hash = "sha256:97712e0d0af05febd8ab63d2ef0ab2d0cd9deddf4476f7aa153f76feef4b2754"}, + {file = "regex-2020.6.8-cp38-cp38-win_amd64.whl", hash = "sha256:6ad8663c17db4c5ef438141f99e291c4d4edfeaacc0ce28b5bba2b0bf273d9b5"}, + {file = "regex-2020.6.8.tar.gz", hash = "sha256:e9b64e609d37438f7d6e68c2546d2cb8062f3adb27e6336bc129b51be20773ac"}, +] +requests = [ + {file = "requests-2.24.0-py2.py3-none-any.whl", hash = "sha256:fe75cc94a9443b9246fc7049224f75604b113c36acb93f87b80ed42c44cbb898"}, + {file = "requests-2.24.0.tar.gz", hash = "sha256:b3559a131db72c33ee969480840fff4bb6dd111de7dd27c8ee1f820f4f00231b"}, +] +six = [ + {file = "six-1.15.0-py2.py3-none-any.whl", hash = "sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced"}, + {file = "six-1.15.0.tar.gz", hash = "sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"}, +] +soupsieve = [ + {file = "soupsieve-1.9.6-py2.py3-none-any.whl", hash = "sha256:feb1e937fa26a69e08436aad4a9037cd7e1d4c7212909502ba30701247ff8abd"}, + {file = "soupsieve-1.9.6.tar.gz", hash = "sha256:7985bacc98c34923a439967c1a602dc4f1e15f923b6fcf02344184f86cc7efaa"}, +] +tzlocal = [ + {file = "tzlocal-2.1-py2.py3-none-any.whl", hash = "sha256:e2cb6c6b5b604af38597403e9852872d7f534962ae2954c7f35efcb1ccacf4a4"}, + {file = "tzlocal-2.1.tar.gz", hash = "sha256:643c97c5294aedc737780a49d9df30889321cbe1204eac2c2ec6134035a92e44"}, +] +urllib3 = [ + {file = "urllib3-1.25.9-py2.py3-none-any.whl", hash = "sha256:88206b0eb87e6d677d424843ac5209e3fb9d0190d0ee169599165ec25e9d9115"}, + {file = "urllib3-1.25.9.tar.gz", hash = "sha256:3018294ebefce6572a474f0604c2021e33b3fd8006ecd11d62107a5d2a963527"}, +] diff --git a/pygooglenews/__init__.py b/pygooglenews/__init__.py new file mode 100644 index 0000000..e0e6ed2 --- /dev/null +++ b/pygooglenews/__init__.py @@ -0,0 +1,153 @@ +import feedparser +from bs4 import BeautifulSoup +import urllib +from dateparser import parse as parse_date +import requests + + + +class GoogleNews: + def __init__(self, lang = 'en', country = 'US'): + self.lang = lang.lower() + self.country = country.upper() + self.BASE_URL = 'https://news.google.com/rss' + + def __top_news_parser(self, text): + """Return subarticles from the main and topic feeds""" + try: + bs4_html = BeautifulSoup(text, "html.parser") + # find all li tags + lis = bs4_html.find_all('li') + sub_articles = [] + for li in lis: + try: + sub_articles.append({"url": li.a['href'], + "title": li.a.text, + "publisher": li.font.text}) + except: + pass + return sub_articles + except: + return text + + def __ceid(self): + """Compile correct country-lang parameters for Google News RSS URL""" + return '?ceid={}:{}'.format(self.country,self.lang) + + def __add_sub_articles(self, entries): + for i, val in enumerate(entries): + if 'summary' in entries[i].keys(): + entries[i]['sub_articles'] = self.__top_news_parser(entries[i]['summary']) + else: + entries[i]['sub_articles'] = None + return entries + + def __scaping_bee_request(self, api_key, url): + response = requests.get( + url="https://app.scrapingbee.com/api/v1/", + params={ + "api_key": api_key, + "url": url, + "render_js": "false" + } + ) + if response.status_code == 200: + return response + if response.status_code != 200: + raise Exception("ScrapingBee status_code: " + str(response.status_code) + " " + response.text) + + def __parse_feed(self, feed_url, proxies=None, scraping_bee = None): + + if scraping_bee and proxies: + raise Exception("Pick either ScrapingBee or proxies. Not both!") + + if proxies: + r = requests.get(feed_url, proxies = proxies) + else: + r = requests.get(feed_url) + + if scraping_bee: + r = self.__scaping_bee_request(url = feed_url, api_key = scraping_bee) + else: + r = requests.get(feed_url) + + + if 'https://news.google.com/rss/unsupported' in r.url: + raise Exception('This feed is not available') + + d = feedparser.parse(r.text) + return dict((k, d[k]) for k in ('feed', 'entries')) + + def __search_helper(self, query): + return urllib.parse.quote_plus(query) + + def __from_to_helper(self, validate=None): + try: + validate = parse_date(validate).strftime('%Y-%m-%d') + return str(validate) + except: + raise Exception('Could not parse your date') + + + + def top_news(self, proxies=None, scraping_bee = None): + """Return a list of all articles from the main page of Google News + given a country and a language""" + d = self.__parse_feed(self.BASE_URL + self.__ceid(), proxies=proxies, scraping_bee=scraping_bee) + d['entries'] = self.__add_sub_articles(d['entries']) + return d + + def topic_headlines(self, topic: str, proxies=None, scraping_bee=None): + """Return a list of all articles from the topic page of Google News + given a country and a language""" + #topic = topic.upper() + if topic.upper() in ['WORLD', 'NATION', 'BUSINESS', 'TECHNOLOGY', 'ENTERTAINMENT', 'SCIENCE', 'SPORTS', 'HEALTH']: + d = self.__parse_feed(self.BASE_URL + '/headlines/section/topic/{}'.format(topic.upper()) + self.__ceid(), proxies = proxies, scraping_bee=scraping_bee) + + else: + d = self.__parse_feed(self.BASE_URL + '/topics/{}'.format(topic) + self.__ceid(), proxies = proxies, scraping_bee=scraping_bee) + + d['entries'] = self.__add_sub_articles(d['entries']) + if len(d['entries']) > 0: + return d + else: + raise Exception('unsupported topic') + + def geo_headlines(self, geo: str, proxies=None, scraping_bee=None): + """Return a list of all articles about a specific geolocation + given a country and a language""" + d = self.__parse_feed(self.BASE_URL + '/headlines/section/geo/{}'.format(geo) + self.__ceid(), proxies = proxies, scraping_bee=scraping_bee) + + d['entries'] = self.__add_sub_articles(d['entries']) + return d + + def search(self, query: str, helper = True, when = None, from_ = None, to_ = None, proxies=None, scraping_bee=None): + """ + Return a list of all articles given a full-text search parameter, + a country and a language + + :param bool helper: When True helps with URL quoting + :param str when: Sets a time range for the artiles that can be found + """ + + if when: + query += ' when:' + when + + if from_ and not when: + from_ = self.__from_to_helper(validate=from_) + query += ' after:' + from_ + + if to_ and not when: + to_ = self.__from_to_helper(validate=to_) + query += ' before:' + to_ + + if helper == True: + query = self.__search_helper(query) + + search_ceid = self.__ceid() + search_ceid = search_ceid.replace('?', '&') + + d = self.__parse_feed(self.BASE_URL + '/search?q={}'.format(query) + search_ceid, proxies = proxies, scraping_bee=scraping_bee) + + d['entries'] = self.__add_sub_articles(d['entries']) + return d \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..957955d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,23 @@ +[tool.poetry] +name = "pygooglenews" +version = "0.1.0" +description = "If Google News had a Python library" +authors = ["kotartemiy "] +license = "MIT" +readme = "README.md" +homepage = "https://www.newscatcherapi.com" +keywords = ["News", "RSS", "Scraping", "Data Mining"] + + +[tool.poetry.dependencies] +python = "^3.6" +feedparser = "^5.2.1" +beautifulsoup4 = "^4.9.1" +dateparser = "^0.7.6" +requests = "^2.24.0" + +[tool.poetry.dev-dependencies] + +[build-system] +requires = ["poetry>=0.12"] +build-backend = "poetry.masonry.api"