插件窝 干货文章 Python爬取微博评论乱码:Unicode方向控制符解决方案

Python爬取微博评论乱码:Unicode方向控制符解决方案

Python爬取微博评论乱码:Unicode方向控制符解决方案

在使用Python爬取微博评论时,开发者经常会遇到评论内容出现乱码或特殊符号的问题,其中Unicode方向控制符(Bidirectional Control Characters)是最常见的干扰因素之一。本文将深入分析问题原因并提供完整的解决方案。

一、问题现象分析

当使用requests或selenium等工具爬取微博评论时,获取的文本中可能出现以下异常:

  • 评论内容被特殊符号(如‪、‫、‬等)包裹
  • 文字顺序显示混乱
  • 部分字符变成问号或方框

二、根本原因

微博国际版为支持多语言混排,会插入Unicode方向控制符:

  • U+202A - 从左到右嵌入
  • U+202B - 从右到左嵌入
  • U+202C - 结束嵌入
  • U+200E - 从左到右标记
  • U+200F - 从右到左标记

三、解决方案

方法1:正则表达式过滤

import re

def clean_text(text):
    # 移除Unicode方向控制符
    return re.sub(r'[\u202a-\u202e\u200e\u200f]', '', text)

方法2:使用unicodedata规范化

import unicodedata

def normalize_text(text):
    # 标准化Unicode并过滤控制字符
    return ''.join(
        char for char in unicodedata.normalize('NFKC', text)
        if not unicodedata.category(char).startswith('C')
    )

方法3:结合BeautifulSoup处理

from bs4 import BeautifulSoup
import re

def clean_html_content(html):
    soup = BeautifulSoup(html, 'lxml')
    text = soup.get_text()
    return re.sub(r'[\u202a-\u202e\u200e\u200f]', '', text)

四、完整爬虫示例

import requests
import re
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)...'
}

def get_weibo_comments(weibo_id):
    url = f'https://weibo.com/ajax/statuses/buildComments?...&id={weibo_id}'
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        data = response.json()
        comments = []
        
        for item in data['data']:
            text = item['text']
            # 清理HTML标签和Unicode控制符
            clean_text = re.sub(r'<[^>]+>', '', text)
            clean_text = re.sub(r'[\u202a-\u202e\u200e\u200f]', '', clean_text)
            comments.append(clean_text)
            
        return comments
    else:
        print(f'请求失败,状态码:{response.status_code}')
        return []

五、注意事项

  1. 微博的反爬机制较严格,建议合理设置请求间隔
  2. 部分特殊字符可能是表情符号的编码,需区别处理
  3. 建议配合使用chardet检测实际编码
  4. 移动端API返回的数据通常比网页端更规范

通过以上方法,您可以有效解决Python爬取微博评论时的Unicode方向控制符导致的乱码问题,获取干净的评论内容。