-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewsSearch.py
executable file
·68 lines (56 loc) · 2.01 KB
/
newsSearch.py
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
#!/bin/python3
import sys
import requests
import json
import argparse
# funcion call help of that script in cmd
def Help():
parser = argparse.ArgumentParser(
prog = "newsSearch.py",
description = "Script process a news API api response and return lists of articles about typed keyword",
)
parser.add_argument("-f", "--file", action="store_true")
parser.add_argument("APIkey")
parser.add_argument("keyword")
args=parser.parse_args()
return args
def OutputToFile(APIresponse):
# ToDo:
# function output file
pass
# funcion send API request and return an API response as dict
def APIcall(APIkey:str, keyword:str) -> dict:
try:
url = f"https://newsapi.org/v2/everything?q={keyword}&apiKey={APIkey}"
return json.loads(requests.get(url).text)
except:
# if something goes wrong then script exits with error code -1
sys.exit(-1)
# function interpets an API response
def APIresponseInterpreter(APIkey:str, keyword:str, isFile = False):
try:
APIresponse = APIcall(APIkey, keyword)
# if API response isn't ok, then script exit with error code -1
if APIresponse["status"] != "ok":
sys.exit(-1)
if help.file:
OutputToFile(APIresponse)
else:
# printing a header
print(f"lists of articles about {keyword}:\n")
# loop lists an articles
for iterator in range(len(APIresponse["articles"])):
print("author: "+str(APIresponse["articles"][iterator]["author"])+
"\ntitle: "+APIresponse["articles"][iterator]["title"]+
"\nurl: "+APIresponse["articles"][iterator]["url"]+"\n")
except:
# if something goes wrong, program exits with error code -1
sys.exit(-1)
# main function
# sys.argv[1] - API key
# sys.argv[2] - keyword of news
if __name__ == "__main__":
help = Help()
APIkey = sys.argv[1]
keyword = sys.argv[2]
APIresponseInterpreter(APIkey, keyword, help.)