-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnews_automator.py
More file actions
73 lines (57 loc) · 1.96 KB
/
news_automator.py
File metadata and controls
73 lines (57 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import requests,os
from sys import argv
API_KEY = 'Your Api Key'
URL = ('https://newsapi.org/v2/top-headlines?')
def get_artciles_by_category(category="technology"):
query_parameters = {
"category": category,
"sortBy": "top",
"country": "ng",
"apiKey": API_KEY
}
return _get_articles(query_parameters)
def get_artciles_by_query(query):
query_parameters = {
"q": query,
"sortBy": "top",
"country": "gb",
"apiKey": API_KEY
}
return _get_articles(query_parameters)
def _get_articles(params):
response = requests.get(URL, params=params)
articles = response.json()['articles']
results = []
for article in articles:
results.append({"title": article["title"], "url": article["url"]})
for result in results:
print(result['title'])
print(result['url'])
print('')
with open('news.txt', 'a') as news:
news.write(f"\n{result['title']}\nLink: {result['url']}\n")
def get_sources_by_category(category):
url = 'https://newsapi.org/v2/top-headlines/sources'
query_parameters = {
"category": category,
"language": "en",
"apiKey": API_KEY
}
response = requests.get(url, params=query_parameters)
sources = response.json()['sources']
for source in sources:
print(source['name'])
print(source['url'])
if __name__ == "__main__":
try:
print(f"Getting news for {argv[1]}...\n")
get_artciles_by_category(argv[1])
print(f"Successfully retrieved top {argv[1]} headlines")
print(f'Saved in a news.txt file at {os.getcwd()}')
except IndexError:
print("Getting news for technology...\n")
get_artciles_by_category()
print("Successfully retrieved top tech headlines")
print(f'Saved in a news.txt file at {os.getcwd()}')
# get_artciles_by_query("Liz Truss"))
#print_sources_by_category("technology")