在使用Python爬取微博评论时,开发者经常会遇到评论内容出现乱码或特殊符号的问题,其中Unicode方向控制符(Bidirectional Control Characters)是最常见的干扰因素之一。本文将深入分析问题原因并提供完整的解决方案。
当使用requests或selenium等工具爬取微博评论时,获取的文本中可能出现以下异常:
微博国际版为支持多语言混排,会插入Unicode方向控制符:
import re
def clean_text(text):
# 移除Unicode方向控制符
return re.sub(r'[\u202a-\u202e\u200e\u200f]', '', text)
import unicodedata
def normalize_text(text):
# 标准化Unicode并过滤控制字符
return ''.join(
char for char in unicodedata.normalize('NFKC', text)
if not unicodedata.category(char).startswith('C')
)
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 []
通过以上方法,您可以有效解决Python爬取微博评论时的Unicode方向控制符导致的乱码问题,获取干净的评论内容。