#coding: utf8import re #正则表达式模块import urllib2 #获取URLs的组件import timefrom Queue import Queueimport threading, errno, datetimeimport jsonimport requests #Requests is an Apache2 Licensed HTTP libraryimport MySQLdb as mdbDB_HOST = '127.0.0.1'DB_USER = 'root'DB_PASS = ''#以下是正则匹配规则re_start = re.compile(r'start=(\d+)') #\d 表示0-9 任意一个数字 后面有+号 说明这个0-9单个数位出现一到多次 比如21312314re_uid = re.compile(r'query_uk=(\d+)') #查询编号re_urlid = re.compile(r'&urlid=(\d+)') #url编号ONEPAGE = 20 #一页数据量ONESHAREPAGE = 20 #一页分享连接量#缺少专辑列表URL_SHARE = 'http://yun.baidu.com/pcloud/feed/getsharelist?auth_type=1&start={start}&limit=20&query_uk={uk}&urlid={id}' #获得分享列表URL_FOLLOW = 'http://yun.baidu.com/pcloud/friend/getfollowlist?query_uk={uk}&limit=20&start={start}&urlid={id}' #获得订阅列表URL_FANS = 'http://yun.baidu.com/pcloud/friend/getfanslist?query_uk={uk}&limit=20&start={start}&urlid={id}' # 获取关注列表QNUM = 1000hc_q = Queue(20) #请求队列hc_r = Queue(QNUM) #接收队列success = 0failed = 0def req_worker(inx): #请求s = requests.Session() #请求对象while True:req_item = hc_q.get() #获得请求项req_type = req_item[0] #请求类型,分享?订阅?粉丝?url = req_item[1] #urlr = s.get(url) #通过url获得数据hc_r.put((r.text, url)) #将获得数据文本和url放入接收队列print "req_worker#", inx, url #inx 线程编号; url 分析了的 urldef response_worker(): #处理工作dbconn = mdb.connect(DB_HOST, DB_USER, DB_PASS, 'baiduyun', charset='utf8')dbcurr = dbconn.cursor()dbcurr.execute('SET NAMES utf8')dbcurr.execute('set global wait_timeout=60000') #以上皆是数据库操作while True:"""#正则备注match() 决定 RE 是否在字符串刚开始的位置匹配search() 扫描字符串,找到这个 RE 匹配的位置findall() 找到 RE 匹配的所有子串,并把它们作为一个列表返回finditer() 找到 RE 匹配的所有子串,并把它们作为一个迭代器返回百度页面链接:http://pan.baidu.com/share/link?shareid=3685432306&uk=1798788396&from=hotrecuk 其实用户id值"""metadata, effective_url = hc_r.get() #获得metadata(也就是前面的r.text)和有效的url#print "response_worker:", effective_urltry:tnow = int(time.time()) #获得当前时间id = re_urlid.findall(effective_url)[0] #获得re_urlid用户编号start = re_start.findall(effective_url)[0] #获得start用户编号if True:if 'getfollowlist' in effective_url: #type = 1,也就是订阅类follows = json.loads(metadata) #以将文本数据转化成json数据格式返回uid = re_uid.findall(effective_url)[0] #获得re_uid,查询编号if "total_count" in follows.keys() and follows["total_count"]>0 and str(start) == "0": #获得订阅数量for i in range((follows["total_count"]-1)/ONEPAGE): #开始一页一页获取有用信息try:dbcurr.execute('INSERT INTO urlids(uk, start, limited, type, status) VALUES(%s, %s, %s, 1, 0)' % (uid, str(ONEPAGE*(i+1)), str(ONEPAGE)))#存储url编号,订阅中有用户编号,start表示从多少条数据开始获取,初始status=0为未分析状态except Exception as ex:print "E1", str(ex)passif "follow_list" in follows.keys(): #如果订阅者也订阅了,即拥有follow_listfor item in follows["follow_list"]:try:dbcurr.execute('INSERT INTO user(userid, username, files, status, downloaded, lastaccess) VALUES(%s, "%s", 0, 0, 0, %s)' % (item['follow_uk'], item['follow_uname'], str(tnow)))#存储订阅这的用户编号,用户名,入库时间except Exception as ex:print "E13", str(ex)passelse:print "delete 1", uid, startdbcurr.execute('delete from urlids where uk=%s and type=1 and start>%s' % (uid, start))elif 'getfanslist' in effective_url: #type = 2,也就是粉丝列表fans = json.loads(metadata)uid = re_uid.findall(effective_url)[0]if "total_count" in fans.keys() and fans["total_count"]>0 and str(start) == "0":for i in range((fans["total_count"]-1)/ONEPAGE):try:dbcurr.execute('INSERT INTO urlids(uk, start, limited, type, status) VALUES(%s, %s, %s, 2, 0)' % (uid, str(ONEPAGE*(i+1)), str(ONEPAGE)))except Exception as ex:print "E2", str(ex)passif "fans_list" in fans.keys():for item in fans["fans_list"]:try:dbcurr.execute('INSERT INTO user(userid, username, files, status, downloaded, lastaccess) VALUES(%s, "%s", 0, 0, 0, %s)' % (item['fans_uk'], item['fans_uname'], str(tnow)))except Exception as ex:print "E23", str(ex)passelse:print "delete 2", uid, startdbcurr.execute('delete from urlids where uk=%s and type=2 and start>%s' % (uid, start))else: #type=0,也即是分享列表shares = json.loads(metadata)uid = re_uid.findall(effective_url)[0]if "total_count" in shares.keys() and shares["total_count"]>0 and str(start) == "0":for i in range((shares["total_count"]-1)/ONESHAREPAGE):try:dbcurr.execute('INSERT INTO urlids(uk, start, limited, type, status) VALUES(%s, %s, %s, 0, 0)' % (uid, str(ONESHAREPAGE*(i+1)), str(ONESHAREPAGE)))except Exception as ex:print "E3", str(ex)passif "records" in shares.keys():for item in shares["records"]:try:dbcurr.execute('INSERT INTO share(userid, filename, shareid, status) VALUES(%s, "%s", %s, 0)' % (uid, item['title'], item['shareid'])) #item['title']恰好是文件名称#返回的json信息:except Exception as ex:#print "E33", str(ex), itempasselse:print "delete 0", uid, startdbcurr.execute('delete from urlids where uk=%s and type=0 and start>%s' % (uid, str(start)))dbcurr.execute('delete from urlids where id=%s' % (id, ))dbconn.commit()except Exception as ex:print "E5", str(ex), iddbcurr.close()dbconn.close() #关闭数据库def worker():global success, faileddbconn = mdb.connect(DB_HOST, DB_USER, DB_PASS, 'baiduyun', charset='utf8')dbcurr = dbconn.cursor()dbcurr.execute('SET NAMES utf8')dbcurr.execute('set global wait_timeout=60000')#以上是数据库相关设置while True:#dbcurr.execute('select * from urlids where status=0 order by type limit 1')dbcurr.execute('select * from urlids where status=0 and type>0 limit 1') #type>0,为非分享列表d = dbcurr.fetchall()#每次取出一条数据出来#print dif d: #如果数据存在id = d[0][0] #请求url编号uk = d[0][1] #用户编号start = d[0][2]limit = d[0][3]type = d[0][4] #哪种类型dbcurr.execute('update urlids set status=1 where id=%s' % (str(id),)) #状态更新为1,已经访问过了url = ""if type == 0: #分享url = URL_SHARE.format(uk=uk, start=start, id=id).encode('utf-8') #分享列表格式化#query_uk uk 查询编号#start#urlid id url编号elif type == 1: #订阅url = URL_FOLLOW.format(uk=uk, start=start, id=id).encode('utf-8') #订阅列表格式化elif type == 2: #粉丝url = URL_FANS.format(uk=uk, start=start, id=id).encode('utf-8') #关注列表格式化if url:hc_q.put((type, url)) #如果url存在,则放入请求队列,type表示从哪里获得数据#通过以上的url就可以获得相应情况下的数据的json数据格式,如分享信息的,订阅信息的,粉丝信息的#print "processed", urlelse: #否则从订阅者或者粉丝的引出人中获得信息来存储,这个过程是爬虫树的下一层扩展dbcurr.execute('select * from user where status=0 limit 1000')d = dbcurr.fetchall()if d:for item in d:try:dbcurr.execute('insert into urlids(uk, start, limited, type, status) values("%s", 0, %s, 0, 0)' % (item[1], str(ONESHAREPAGE)))#uk 查询号,其实是用户编号#start 从第1条数据出发获取信息#dbcurr.execute('insert into urlids(uk, start, limited, type, status) values("%s", 0, %s, 1, 0)' % (item[1], str(ONEPAGE)))dbcurr.execute('insert into urlids(uk, start, limited, type, status) values("%s", 0, %s, 2, 0)' % (item[1], str(ONEPAGE)))dbcurr.execute('update user set status=1 where userid=%s' % (item[1],)) #做个标志,该条数据已经访问过了#跟新了分享,订阅,粉丝三部分数据except Exception as ex:print "E6", str(ex)else:time.sleep(1)dbconn.commit()dbcurr.close()dbconn.close()def main():print 'starting at:',now()for item in range(16): t = threading.Thread(target = req_worker, args = (item,))t.setDaemon(True)t.start() #请求线程开启,共开启16个线程s = threading.Thread(target = worker, args = ())s.setDaemon(True)s.start() #worker线程开启response_worker() #response_worker开始工作print 'all Done at:', now()
进一步交流学习可以点击查看小编的个人资料,有惊喜!