How to Detect Who Blocked You on QQ Space with Python and Selenium

This guide shows how to use Python, Selenium, and requests to log into QQ Space, retrieve authentication cookies, compute the required g_tk token, fetch the full friend list via QQ's API, identify users who have blocked you, and optionally blacklist them automatically.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
How to Detect Who Blocked You on QQ Space with Python and Selenium

Preparation

Set up a Python 3.7.4 environment and install the required third‑party libraries: requests, lxml, threadpool, and selenium.

python environment:
python3.7.4
third‑party libraries:
requests
lxml
threadpool
selenium

Login with Selenium and Save Cookie

Use a headless Chrome driver to open https://i.qq.com/, switch to the login frame, fill in the QQ number and password, click the login button, and then extract all cookies. The cookies are saved as a JSON dictionary in cookie_dict.txt.

def search_cookie():
    if not __import__('os').path.exists('cookie_dict.txt'):
        get_cookie_json()
    with open('cookie_dict.txt', 'r') as f:
        cookie = json.load(f)
    return cookie

def get_cookie_json():
    qq_number = input('请输入qq号:')
    password = __import__('getpass').getpass('请输入qq密码:')
    from selenium import webdriver
    login_url = 'https://i.qq.com/'
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(login_url)
    driver.switch_to.frame('login_frame')
    driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="u"]').send_keys(qq_number)
    driver.find_element_by_xpath('//*[@id="p"]').send_keys(password)
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="login_button"]').click()
    time.sleep(1)
    cookie_list = driver.get_cookies()
    cookie_dict = {}
    for cookie in cookie_list:
        if 'name' in cookie and 'value' in cookie:
            cookie_dict[cookie['name']] = cookie['value']
    with open('cookie_dict.txt', 'w') as f:
        json.dump(cookie_dict, f)
    return True

Find the Friend‑List API

Open your own QQ Space, press F12 , clear the Network panel, then click the Friends tab. The request URL contains a friend field that returns the friend list. Save the URL for later use.

Network panel showing friend request
Network panel showing friend request
Friend request details
Friend request details

Decrypt the g_tk Parameter

The request requires a g_tk token generated from the p_skey cookie. The following function implements the algorithm.

def get_g_tk():
    # QQ空间的加密算法
    p_skey = cookie['p_skey']
    h = 5381
    for i in p_skey:
        h += (h << 5) + ord(i)
    g_tk = h & 2147483647
    return g_tk

Retrieve the Friend List

With the g_tk value, construct the API URL and request the JSON data. Extract the uin (QQ number) of each friend.

def get_friends_uin(g_tk):
    # 获得好友的QQ号信息
    yurl = 'https://user.qzone.qq.com/proxy/domain/r.qzone.qq.com/cgi-bin/tfriend/friend_ship_manager.cgi?'
    data = {
        'uin': cookie['ptui_loginuin'],
        'do': 1,
        'g_tk': g_tk
    }
    url = yurl + urllib.parse.urlencode(data)
    res = requests.get(url, headers=headers, cookies=cookie)
    r = res.text.split('(')[1].split(')')[0]
    friends_list = json.loads(r)['data']['items_list']
    friends_uin = []
    for f in friends_list:
        friends_uin.append(f['uin'])
    return friends_uin

Identify Blocked Users

Visit each friend's space URL. If the page contains a permission‑denied message, record that QQ number as a blocked user.

def get_blacklist(friends):
    # 查询被挡好友的QQ号,用小本本记下来!
    access_denied = []
    yurl = 'https://user.qzone.qq.com/'
    for friend in friends:
        print('开始检查:' + str(friend))
        url = yurl + str(friend)
        res = requests.get(url, headers=headers, cookies=cookie)
        tip = etree.HTML(res.text).xpath('/html/body/div/div/div[1]/p/text()')
        if len(tip) > 0:
            print(str(friend) + '把我拉黑了!')
            access_denied.append(friend)
    return access_denied

Blacklist the Blockers

For each blocked QQ number, send a POST request to the QQ Space blacklist API using the previously computed g_tk. This removes them from your friend list.

def pull_black():
    # 拉黑,必须拉黑!
    global cookie
    cookie = search_cookie()
    with open('access_denied.txt', 'r') as f:
        access_denied = f.readlines()
    for fake_friend in access_denied:
        fake_friend = fake_friend.split('
')[0]
        yurl = "https://user.qzone.qq.com/proxy/domain/w.qzone.qq.com/cgi-bin/right/cgi_black_action_new?"
        g_tk = get_g_tk()
        url_data = {'g_tk': g_tk}
        data = {
            'uin': cookie['ptui_loginuin'],
            'action': '1',
            'act_uin': fake_friend,
            'fupdate': '1',
            'qzreferrer': 'https://user.qzone.qq.com/1223411083'
        }
        url = yurl + urllib.parse.urlencode(url_data)
        res = requests.post(url, headers=headers, data=data, cookies=cookie)
        print(str(fake_friend) + '已被您拉黑')
    print('都拉黑了!解气!!')

Result

Running the script prints the QQ numbers that have blocked you and automatically adds them to your blacklist, giving you a clear view of who has hidden your profile.

Pythonautomationweb-scrapingQQ SpaceseleniumcookieBlocking Detection
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.