-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
83 lines (69 loc) · 2.91 KB
/
api.py
File metadata and controls
83 lines (69 loc) · 2.91 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
74
75
76
77
78
79
80
81
82
83
import urllib.parse
import requests
############ SEARCH QUERY URLS ############
def titletagquery(keyword):
query="/2.2/search/advanced?order=desc&sort=votes&q=["
query+=keyword+"]&accepted=True&title="
query+=keyword+"&site=stackoverflow&filter=!-*jbN-o8P3E5"
return query
def tagquery(keyword):
query="/2.2/search/advanced?order=desc&sort=votes&q=["
query+=keyword+"]&accepted=True&site=stackoverflow&filter=!-*jbN-o8P3E5"
return query
def titlequery(keyword):
query="/2.2/search/advanced?order=desc&sort=votes&accepted=True&title="
query+=keyword+"&site=stackoverflow&filter=!-*jbN-o8P3E5"
return query
###########################################
######### Creating HTML File ##############
class CreateHTML:
def __init__(self,name):
self.name=name
self.createtemplate(self.name)
#HTML Template (before body)
def createtemplate(self,name):
with open(name+".html","w") as f:
f.write("""<!DOCTYPE html>
<html>
<head>
<title>"""+name+"""</title>
</head>
<body>
""")
#Appending data to HTML File
def writedata(self,title,body,ans):
with open(self.name+".html","a") as f:
f.write("<h1>"+title+"</h1>\n"+body+"\n\n<h1>Answer:</h1>\n"+ans+"\n<hr>\n")
#Fetching Data
def getquestion(self,keyword):
try:
main_api='https://api.stackexchange.com/'
query=titletagquery(keyword)
r=requests.get(main_api+query)
json_object=r.json()
#Search query preference order: title+tag -> title -> tag
if json_object["items"]==[]:
query=titlequery(keyword)
r=requests.get(main_api+query)
json_object=r.json()
if json_object["items"]==[]:
query=tagquery(keyword)
r=requests.get(main_api+query)
json_object=r.json()
if json_object["item"]==[]:
raise Exception
temp_qtitle=str(json_object["items"][0]["title"]) #0 for first question and its answer set
temp_qbody=str(json_object["items"][0]["body"]) #body for first question
temp_ans=str(json_object["items"][0]["answers"][0]["body"]) #first retrieved answer's body
self.writedata(temp_qtitle,temp_qbody,temp_ans)
except:
print("No data could be found. Keyword: "+keyword)
def addquestion(self,keyword):
self.getquestion(keyword)
# IMPORTANT! Closes the HTML tags including body
def endquestion(self):
with open(self.name+".html","a") as f:
f.write("</body></html>")
"""
/2.2/search/advanced?order=desc&sort=votes&accepted=True&title=ACM&site=stackoverflow&filter=!-*jbN-o8P3E5
"""