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
| import json import time import urllib.request import re import pymssql from hashlib import md5 import threading import inspect import ctypes temp='' lock=False opts=[] timu='' selectNum=1 k=['A','B','C','D'] url = 'https://www.baidu.com/s?wd=%' headers = ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393") opener = None reg_o2=re.compile('.') reg_o3=re.compile('[。“”,]')
def useProxy(proxy_addr): global opener proxy = urllib.request.ProxyHandler({'http': proxy_addr}) opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler) opener.addheaders = [headers] urllib.request.install_opener(opener) useProxy('61.135.217.7')
def getMD5(strs): myMD=md5() myMD.update(strs.encode('utf-8')) return myMD.hexdigest()
def check(cursor,cmd,mod=0): cursor.execute(cmd) if cursor.rowcount: if mod==1: for row in cursor: return row[1] return True else: return False
def addRecord(conn,cursor,cmd,strs_md5): try: checkSql="select * from bank1 where md5='"+strs_md5+"'" if(not check(cursor,checkSql)): cursor.execute(cmd) conn.commit() except Exception as e: print(str(e)) def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread): _async_raise(thread.ident, SystemExit) def main(): global temp,lock,opts,timu while True: with open('E:\\TEST\\weibo\\responseBody.txt',encoding='utf-8') as f: try: j=json.loads(f.read()) if 'quiz' in j['data']: quiz=j['data']['quiz'] if quiz==temp: pass else: temp=quiz lock=True print(str(j['data']['num'])+'. '+'['+j['data']['school']+'/'+j['data']['type']+'] '+quiz) timu=quiz opts=j['data']['options'] print('A:%s B:%s C:%s D:%s'%(opts[0],opts[1],opts[2],opts[3])) def SearchEngines(): global selectNum data = urllib.request.urlopen(url+urllib.parse.quote(quiz),timeout=1.5).read().decode('utf-8') regs=[] for i in opts: regs.append(reg_o2.sub(lambda match:match.group(0)+'[^'+match.group(0)+']*?',i)[:-6]) reg_4=re.compile('('+regs[0]+'|'+regs[1]+'|'+regs[2]+'|'+regs[3]+')') maxs=[0,0,0,0] def replacement(match): string=match.group(1) for index,i in enumerate(regs): if re.findall(i,string): maxs[index]+=1 break return '' reg_4.sub(replacement,data) maxindex=0 for index,i in enumerate(maxs): if i > maxs[maxindex]: maxindex=index selectNum=maxindex+1 print('\n搜索结果(Internet): '+opts[maxindex]+' 选择【'+k[maxindex]+'】') def SearchDB(): t2=threading.Thread(target=SearchEngines) t2.start() conn = pymssql.connect(host='.',user='sa',password='s17a0114da',database='QuestionBank') cursor=conn.cursor() retrieveSql="select * from bank1 where md5='"+getMD5(quiz)+"'" right=check(cursor,retrieveSql,1) if not right: print('数据库无结果') else: stop_thread(t2) xiabiao=(xb for xb,it in enumerate(opts) if it==right) print('\n搜索结果(DataBase): '+right+' 选择【'+k[next(xiabiao)]+'】') cursor.close() conn.close() t1=threading.Thread(target=SearchDB) t1.start() t1.join() else: if lock: lock=False if(not j['data']['yes'] or j['data']['answer']!=selectNum): conn = pymssql.connect(host='.',user='sa',password='s17a0114da',database='QuestionBank') cursor=conn.cursor() timu_md5=getMD5(timu) addSql="insert into bank1 values('"+timu_md5+"','"+opts[j['data']['answer']-1]+"','"+timu+"')" addRecord(conn,cursor,addSql,timu_md5) cursor.close() conn.close() if j['data']['yes']: print('回答【正确】,又加分啦!') else: print('回答【错误】,呜呜呜!') if opts: print('正确答案: '+opts[j['data']['answer']-1]+'\n') except Exception as e: print(str(e)) time.sleep(0.5) if __name__=='__main__': print('头脑王者,就是我!请开启对战!') main()
|