This repository has been archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathapi.py
673 lines (574 loc) · 20 KB
/
api.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# -*- coding: utf-8 -*-
"""
This is the apis of searching the answer.
@author: yanyongyu
"""
__author__ = "yanyongyu"
__all__ = ["cxmooc_tool", "forestpolice", "jiuaidaikan", "xuanxiu365"]
import sys
import json
import logging
import asyncio
# from hashlib import md5
import requests
from lxml import etree
requests.packages.urllib3.disable_warnings()
async def cxmooc_tool(sess: requests.Session,
*args: list) -> list:
# 输入参数处理
if not isinstance(sess, requests.Session):
args = list(args)
args.insert(0, sess)
args = tuple(args)
sess = requests.Session()
# 接口
url = "https://cx.icodef.com/v2/answer"
# 接口参数
index = yield
data = {}
for i in range(len(args)):
data['topic[%d]' % i] = args[i]
# post请求
logging.info("Post to cxmooc_tool api.")
try:
res = sess.post(url, data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
for each in args:
answer = []
answer.append({'topic': str(e),
'correct': ''})
yield answer
raise StopIteration
# 处理结果
logging.info("Processing result")
result = [[] for i in range(len(args))]
for each in res.json():
for answ in each['result']:
temp = {}
temp['topic'] = answ['topic']
temp['correct'] = ''
for option in answ['correct']:
temp['correct'] = temp['correct'] + str(option['option'])
result[each['index']].append(temp)
for i in range(len(result)):
if index and i < index:
continue
logging.info("Yield question %s: %s" % (i+1, result[i]))
index = yield result[i]
raise StopIteration
async def forestpolice(sess: requests.Session,
*args: list) -> list:
# 输入参数处理
if not isinstance(sess, requests.Session):
args = list(args)
args.insert(0, sess)
args = tuple(args)
sess = requests.Session()
# 接口
url = "http://mooc.forestpolice.org/cx/0/"
# 接口参数
index = yield
data = {}
for i in range(len(args)):
if index and i < index:
continue
data['course'] = ""
data['type'] = ""
data['option'] = ""
# post请求
logging.info("Post to forest police. Question %d" % i)
try:
res = sess.post(url + args[i], data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
index = yield answer
continue
# 处理结果
logging.info("Processing result")
answer = []
temp = {}
temp['topic'] = args[i]
temp['correct'] = res.json()['data']
if temp['correct'] != '未找到答案':
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
index = yield answer
await asyncio.sleep(0.5)
raise StopIteration
async def jiuaidaikan(sess: requests.Session,
*args: list) -> list:
"""
本题库不支持所有可能题目搜索!
"""
# 输入参数处理
if not isinstance(sess, requests.Session):
args = list(args)
args.insert(0, sess)
args = tuple(args)
sess = requests.Session()
# 接口
url = "http://www.92daikan.com/tiku.aspx"
# 接口参数
index = yield
# 获取接口参数
try:
res = sess.get(url, verify=False, timeout=3)
res.raise_for_status()
selector = etree.HTML(res.text)
viewstate = selector.xpath('//*[@id="__VIEWSTATE"]/@value')
eventvalidation = selector.xpath(
'//*[@id="__EVENTVALIDATION"]/@value')
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
index = yield
for i in range(len(args)):
if index and i < index:
continue
answer = []
answer.append({'topic': str(e),
'correct': ''})
yield answer
raise StopIteration
data = {}
data['__VIEWSTATE'] = viewstate
data['__EVENTVALIDATION'] = eventvalidation
data['ctl00$ContentPlaceHolder1$gen'] = '查询'
for i in range(len(args)):
if index and i < index:
continue
data['ctl00$ContentPlaceHolder1$timu'] = args[i]
# post请求
logging.info("Post to 92daikan. Question %d" % i)
try:
res = sess.post(url, data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
index = yield answer
continue
# 处理结果
logging.info("Processing result")
answer = []
selector = etree.HTML(res.text)
temp = {}
temp['topic'] = args[i]
temp['correct'] = selector.xpath('//*[@id="daan"]/text()')[0]
if temp['correct'] != '未找到答案':
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
index = yield answer
await asyncio.sleep(0.5)
raise StopIteration
async def xuanxiu365(sess: requests.Session,
*args: list) -> list:
# 输入参数处理
if not isinstance(sess, requests.Session):
args = list(args)
args.insert(0, sess)
args = tuple(args)
sess = requests.Session()
# 接口
url = "http://tiku.xuanxiu365.com/admin/admin/api.html"
header = {}
header['X-Requested-With'] = "XMLHttpRequest"
# 接口参数
index = yield
payload = {}
for i in range(len(args)):
if index and i < index:
continue
payload['search'] = args[i]
# post请求
logging.info("Post to xuanxiu365. Question %d" % i)
try:
res = sess.get(url, params=payload, headers=header,
verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
index = yield answer
continue
# 处理结果
logging.info("Processing result")
res = res.json()
answer = []
if res['data']:
temp = {}
temp['topic'] = res['data']['title']
temp['correct'] = res['data']['content']
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
index = yield answer
await asyncio.sleep(0.5)
raise StopIteration
async def www150s(sess: requests.Session,
*args: list) -> list:
# 输入参数处理
if not isinstance(sess, requests.Session):
args = list(args)
args.insert(0, sess)
args = tuple(args)
sess = requests.Session()
# 接口
url = "http://www.150s.cn/SearchServlet"
header = {
'X-Requested-With': "XMLHttpRequest"
}
# 接口参数
index = yield
payload = {}
for i in range(len(args)):
if index and i < index:
continue
payload['text'] = args[i]
# post请求
logging.info("Post to www150s. Question %d" % i)
try:
res = sess.get(url, params=payload, headers=header,
verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
index = yield answer
continue
# 处理结果
logging.info("Processing result")
res = res.json()
answer = []
temp = {}
for each in res:
temp['topic'] = each['title']
temp['correct'] = each['answer']
if temp['topic'] == "查无此题,请您换一道题查询!":
break
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
index = yield answer
await asyncio.sleep(0.5)
raise StopIteration
async def wangkebang(sess: requests.Session,
*args: list) -> list:
# 输入参数处理
if not isinstance(sess, requests.Session):
args = list(args)
args.insert(0, sess)
args = tuple(args)
sess = requests.Session()
# 接口
url = "http://wangkebang.top/pc/"
# 接口参数
index = yield
data = {}
for i in range(len(args)):
if index and i < index:
continue
data['w'] = args[i]
# post请求
logging.info("Post to wangkebang api.")
try:
res = sess.post(url, data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
for each in args:
answer = []
answer.append({'topic': str(e),
'correct': ''})
yield answer
raise StopIteration
# 处理结果
logging.info("Processing result")
res.encoding = 'utf-8'
answer = []
selector = etree.HTML(res.text)
temp = {}
temp['topic'] = selector.xpath(
'/html/body/div[3]/div[1]/div/span[1]/strong/text()'
)[0].lstrip(" 题目:\n")
temp['correct'] = selector.xpath(
'/html/body/div[3]/div[1]/div/span[2]/strong/text()'
)[0].lstrip(" 答案:\n")
if temp['topic'] != '啊哦暂无该题':
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
index = yield answer
await asyncio.sleep(0.5)
raise StopIteration
# async def poxiaobbs(sess: requests.Session,
# *args: list) -> list:
# # 输入参数处理
# if not isinstance(sess, requests.Session):
# args = list(args)
# args.insert(0, sess)
# args = tuple(args)
# sess = requests.Session()
# # 接口
# url = "https://cx.poxiaobbs.com/index.php"
# # 接口参数
# index = yield
# data = {}
# for i in range(len(args)):
# if index and i < index:
# continue
# data['tm'] = args[i]
# # post请求
# logging.info("Post to poxiao bbs php. Question %d" % i)
# try:
# res = sess.post(url, data=data, verify=False, timeout=5)
# res.raise_for_status()
# except requests.exceptions.RequestException as e:
# logging.info("Request Exception appeared: %s" % e)
# answer = []
# answer.append({'topic': str(e),
# 'correct': ''})
# index = yield answer
# continue
# # 处理结果
# logging.info("Processing result")
# answer = []
# selector = etree.HTML(res.text)
# answer_div = selector.xpath('/html/body/div[1]/div[@class="ans"]')
# for each in answer_div:
# temp = {}
# answer_text = each.xpath('string(.)')\
# .strip().replace(' ', '').replace('\n', '')
# if "答案:" in answer_text:
# temp['topic'] = answer_text.split("答案:")[0]
# temp['correct'] = answer_text.split("答案:")[1]
# answer.append(temp)
# logging.info("Yield question %s: %s" % (i+1, answer))
# index = yield answer
# await asyncio.sleep(0.5)
# raise StopIteration
# async def bankroft(sess: requests.Session,
# *args: list) -> list:
# """
# 该接口只有当题目完整时可用!
# 并且有频率限制!
# """
# # 输入参数处理
# if not isinstance(sess, requests.Session):
# args = list(args)
# args.insert(0, sess)
# args = tuple(args)
# sess = requests.Session()
# # 接口
# string_enc = "-b?M#JvMg2y3$JMk"
# url = "http://123.207.19.72/api/query?"
# # 接口参数
# index = yield
# payload = {}
# for i in range(len(args)):
# if index and i < index:
# continue
# md = md5()
# md.update((args[i]+string_enc).encode())
# payload['title'] = args[i]
# payload['enc'] = md.hexdigest()
# # post请求
# logging.info("Get bankroft api. Question %d" % i)
# try:
# res = sess.get(url, params=payload, verify=False, timeout=5)
# res.raise_for_status()
# except requests.exceptions.RequestException as e:
# logging.info("Request Exception appeared: %s" % e)
# answer = []
# answer.append({'topic': str(e),
# 'correct': ''})
# index = yield answer
# continue
# # 处理结果
# logging.info("Processing result")
# answer = []
# json_text = res.json()
# if json_text['code'] == 100:
# temp = {}
# temp['topic'] = args[i]
# temp['correct'] = json_text['data']
# answer.append(temp)
# elif json_text['code'] == 101:
# temp = {}
# temp['topic'] = "题目输入不完整!bankroft接口需要除题目类型外完整题目"
# temp['correct'] = ""
# answer.append(temp)
# else:
# temp = {}
# temp['topic'] = "bankroft接口查询次数已达上限!"
# temp['correct'] = ""
# answer.append(temp)
# logging.info("Yield question %s: %s" % (i+1, answer))
# index = yield answer
# await asyncio.sleep(0.5)
# raise StopIteration
# async def wangke120(sess: requests.Session,
# *args: list) -> list:
# # 输入参数处理
# if not isinstance(sess, requests.Session):
# args = list(args)
# args.insert(0, sess)
# args = tuple(args)
# sess = requests.Session()
# # 接口
# url = "https://wangke120.com/selectCxDb.php"
# # 接口参数
# index = yield
# data = {}
# for i in range(len(args)):
# if index and i < index:
# continue
# data['question'] = args[i]
# # post请求
# logging.info("Post to wangke120. Question %d" % i)
# try:
# res = sess.post(url, data=data, verify=False, timeout=5)
# res.raise_for_status()
# except requests.exceptions.RequestException as e:
# logging.info("Request Exception appeared: %s" % e)
# answer = []
# answer.append({'topic': str(e),
# 'correct': ''})
# index = yield answer
# continue
# # 处理结果
# logging.info("Processing result")
# answer = []
# temp = {}
# temp['topic'] = args[i]
# temp['correct'] = res.text
# if temp['correct'] != '未找到':
# answer.append(temp)
# logging.info("Yield question %s: %s" % (i+1, answer))
# index = yield answer
# await asyncio.sleep(0.5)
# raise StopIteration
# async def fm210(sess: requests.Session,
# *args: list) -> list:
# # 输入参数处理
# if not isinstance(sess, requests.Session):
# args = list(args)
# args.insert(0, sess)
# args = tuple(args)
# sess = requests.Session()
# # 接口
# url = "http://api.fm210.cn/wangke/cx.php?"
# # 接口参数
# index = yield
# payload = {}
# for i in range(len(args)):
# if index and i < index:
# continue
# payload['w'] = args[i]
# # post请求
# logging.info("Post to fm120. Question %d" % i)
# try:
# res = sess.get(url, params=payload, verify=False, timeout=5)
# res.raise_for_status()
# except requests.exceptions.RequestException as e:
# logging.info("Request Exception appeared: %s" % e)
# answer = []
# answer.append({'topic': str(e),
# 'correct': ''})
# index = yield answer
# continue
# # 处理结果
# logging.info("Processing result")
# answer = []
# temp = {}
# try:
# temp['topic'] = res.text.split('\n')[1]
# temp['correct'] = res.text.split('\n')[3]
# if temp['correct'] != '':
# answer.append(temp)
# except IndexError:
# pass
# logging.info("Yield question %s: %s" % (i+1, answer))
# index = yield answer
# await asyncio.sleep(0.5)
# raise StopIteration
async def cmd():
# 获取所有api
api_list = {}
for each in globals().keys():
if each.startswith('_'):
continue
fn = globals()[each]
if callable(fn):
if getattr(fn, '__annotations__', None):
api_list[each] = fn
args = sys.argv[1:]
if not args or "-h" in args:
print("超星查题助手\n\tpython api.py [-json] [-api=] -text=\nusage:")
print("\t-h\tPrint help")
print("\t-json\tReturn json data at last")
print("\t-api\tUsing the specified api\n\t\tapi list:")
for each in api_list.keys():
print("\t\t\t%s" % each)
print("\t-text\tquestion(-text can be used more than one time)")
else:
# 接收命令行参数
text = []
search = None
JSON = False
for each in args:
if each.startswith("-json"):
JSON = True
elif each.startswith("-api="):
if search is not None:
raise ValueError("More than one specified api.")
if each[5:] in api_list:
search = api_list[each[5:]]
else:
raise ValueError("Unknow api. Use -h for help.")
elif each.startswith("-text="):
text.append(each[6:])
else:
ValueError("Unknow option %s. Use -h for help"
% each.split("=")[0])
# 获取答案
answer = [[] for i in range(len(text))]
if not search:
for each in api_list.keys():
remain = [text[i] for i in range(len(text)) if not answer[i]]
if remain:
generator = api_list[each](*remain)
await generator.asend(None)
for i in range(len(text)):
result = await generator.asend(None)
if not result or not result[0]['correct']:
continue
else:
answer[i] = result
else:
if text:
generator = search(*text)
await generator.asend(None)
for i in range(len(text)):
result = await generator.asend(None)
if not result or not result[0]['correct']:
continue
else:
answer[i] = result
if not JSON:
print(answer)
else:
print(json.dumps(answer))
# json.dump(answer, open("anwser.json", "w"))
if __name__ == "__main__":
logging.basicConfig(level=logging.WARN)
loop = asyncio.get_event_loop()
loop.run_until_complete(cmd())