Python 爬虫实战:人人网社交关系图谱构建(登录态保持 + 好友关系解析)

一、引言

人人网作为曾经国内主流的社交平台之一,积累了大量的用户社交关系数据。尽管其活跃度不如从前,但这些数据对于研究社交网络结构、用户行为模式以及信息传播路径仍具有重要价值。通过构建社交关系图谱,可以直观地展示用户之间的连接关系,挖掘潜在的社交圈层和关键节点。

二、开发环境准备

(一)安装 Python

确保安装了 Python 3.7 或以上版本,可从官方网站下载安装。然后安装必要的库:requests、selenium、networkx、matplotlib、pandas、fake-useragent。

(二)安装必要库

pip install requests
pip install selenium
pip install networkx
pip install matplotlib
pip install pandas
pip install fake-useragent

三、登录态保持与好友关系解析

(一)使用 Selenium 模拟登录

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from fake_useragent import UserAgent

# 配置 Selenium 选项
options = webdriver.ChromeOptions()
options.add_argument('--headless')  # 无头模式
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')

# 设置随机 User-Agent
ua = UserAgent()
user_agent = ua.random
options.add_argument(f'user-agent={user_agent}')

# 启动 WebDriver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

# 访问人人网登录页面
login_url = "http://www.renren.com/SysHome.do"
driver.get(login_url)

# 填写登录表单
username = driver.find_element(By.ID, "email")
password = driver.find_element(By.ID, "password")
username.send_keys("your_email")  # 替换为你的邮箱
password.send_keys("your_password")  # 替换为你的密码

# 提交登录表单
login_button = driver.find_element(By.ID, "login")
login_button.click()

# 检查是否登录成功
if "欢迎回来" in driver.page_source:
    print("登录成功!")
else:
    print("登录失败,请检查账号密码。")
    driver.quit()
    exit()

(二)解析好友关系

from bs4 import BeautifulSoup
import time

# 获取好友列表页面
friends_url = "http://www.renren.com/好友列表页面URL"  # 替换为实际好友列表页面的 URL
driver.get(friends_url)

# 等待页面加载
time.sleep(2)

# 获取页面内容
friends_page_source = driver.page_source

# 解析好友列表
soup = BeautifulSoup(friends_page_source, 'html.parser')
friends_list = []

# 假设好友信息在特定的 div 标签中
friends_div = soup.find('div', class_='friends-list')
if friends_div:
    for friend in friends_div.find_all('li', class_='friend-item'):
        friend_info = {}
        # 提取好友的用户名
        username_tag = friend.find('a', class_='username')
        if username_tag:
            friend_info['username'] = username_tag.text.strip()
        else:
            friend_info['username'] = "未知用户名"
        
        # 提取好友的个人主页链接
        profile_link_tag = friend.find('a', class_='profile-link')
        if profile_link_tag and 'href' in profile_link_tag.attrs:
            friend_info['profile_link'] = profile_link_tag['href']
        else:
            friend_info['profile_link'] = "无链接"
        
        friends_list.append(friend_info)

# 打印好友列表
for friend in friends_list:
    print(f"用户名:{friend['username']}, 个人主页链接:{friend['profile_link']}")

# 关闭浏览器
driver.quit()

(三)社交关系图谱构建与可视化

import networkx as nx
import matplotlib.pyplot as plt

# 创建图对象
G = nx.Graph()

# 添加节点和边
for i in range(len(friends_list)):
    for j in range(i + 1, len(friends_list)):
        G.add_edge(friends_list[i]['username'], friends_list[j]['username'])

# 绘制社交关系图谱
plt.figure(figsize=(12, 12))
nx.draw(G, with_labels=True, node_size=500, node_color='skyblue', edge_color='gray', font_size=10)
plt.title('人人网社交关系图谱')
plt.show()

四、数据存储与管理

(一)存储为 CSV 文件

import pandas as pd

# 将好友列表保存为 CSV 文件
df_friends = pd.DataFrame(friends_list)
df_friends.to_csv('renren_friends.csv', index=False, encoding='utf-8-sig')

(二)存储为 JSON 文件

import json

# 将好友列表保存为 JSON 文件
with open('renren_friends.json', 'w', encoding='utf-8') as json_file:
    json.dump(friends_list, json_file, ensure_ascii=False, indent=4)

五、总结与展望

通过上述步骤,我们成功实现了人人网的登录模拟、好友关系解析以及社交关系图谱的构建与可视化。在实际应用中,可以根据需要进一步扩展功能,如批量爬取多个用户的好友关系数据、分析好友之间的互动频率等。同时,需要注意遵守人人网的使用条款和隐私政策,合理使用爬虫技术。

Python 爬虫实战:人人网社交关系图谱构建(登录态保持 + 好友关系解析)_第1张图片

你可能感兴趣的:(python爬虫实战,python,爬虫,开发语言)