Python2.7获取QQ空间全部好友

通过Wireshark抓包,QQ空间有个获取全部好友的接口

URL地址

http://m.qzone.com/friend/mfriend_list?g_tk=1399550749&res_uin=[QQ号码]&res_type=normal&format=json&count_per_page=10&page_index=0&page_type=0&mayknowuin=&qqmailstat=

然后把登录QQ空间之后的cookies字符串带上就行,电脑手机的cookies都行

Python代码如下

# -*- coding: UTF-8 -*-
import httplib2
import json
import re

def LongToInt(value):  # 由于int+int超出范围后自动转为long型,通过这个转回来
    if isinstance(value, int):
        return int(value)
    else:
        return int(value & 0x7fffffff)
def LeftShiftInt(number, step):  # 由于左移可能自动转为long型,通过这个转回来
    if isinstance((number << step), long):
        return int((number << step) - 0x200000000L)
    else:
        return int(number << step)
def getOldGTK(skey):
    a = 5381
    for i in range(0, len(skey)):
        a = a + LeftShiftInt(a, 5) + ord(skey[i])
        a = LongToInt(a)
    return a & 0x7fffffff
def getNewGTK(p_skey, skey, rv2):
    b = p_skey or skey or rv2
    a = 5381
    for i in range(0, len(b)):
        a = a + LeftShiftInt(a, 5) + ord(b[i])
        a = LongToInt(a)
    return a & 0x7fffffff


h = httplib2.Http()
url = 'http://m.qzone.com/friend/mfriend_list?g_tk=1536221140&res_uin=[QQ号码]&res_type=normal&format=json&count_per_page=10&page_index=0&page_type=0&mayknowuin=&qqmailstat='
cookieStr = ''
headers = {'Cookie': cookieStr}
if re.search(r'p_skey=(?P<p_skey>[^;]*)', cookieStr):
    p_skey = re.search(r'p_skey=(?P<p_skey>[^;]*)', cookieStr).group('p_skey')
else:
    p_skey = None
if re.search(r'skey=(?P<skey>[^;]*)', cookieStr):
    skey = re.search(r'skey=(?P<skey>[^;]*)', cookieStr).group('skey')
else:
    skey = None
if re.search(r'rv2=(?P<rv2>[^;]*)', cookieStr):
    rv2 = re.search(r'rv2=(?P<rv2>[^;]*)', cookieStr).group('rv2')
else:
    rv2 = None
print getNewGTK(p_skey, skey, rv2)
url = url.replace('1536221140', str(getNewGTK(p_skey, skey, rv2)))
print url
resp, content = h.request(url, 'GET', headers=headers)
print resp
print content
output = json.loads(content)  # json字符串转字典
if output['code'] == -3000:
    print output['message']
else:
    items_list = output['data']['list']
    qqlist = set()
    for item in items_list:
        qqlist.add(item['uin'])
    # 打印信息并输出到文件
    print '获取QQ号个数'+ str(len(qqlist))
    filename = 'qqlist.txt'
    fileobj = open(filename, 'w')
    result = [str(qq) + '\n' for qq in sorted(qqlist)]
    fileobj.writelines(result)
    fileobj.flush()
    fileobj.close()
    print '写入完成'


使用时注意替换掉url中的[QQ号码]和headers中的CookieStr

后记:

20150904更新:由于上一版代码没考虑到g_tk取值的问题,导致代码不能重用,现已更改。




你可能感兴趣的:(python,QQ空间,好友列表)