超级方便的微博用户信息爬虫
点击上方 月小水长 并 设为星标,第一时间接收干货推送
今天更新的是微博用户信息爬虫,不是用户爬虫,用户爬虫爬的用户主页发过的微博,用户爬虫用 cn 站的还可以用 一个爬取用户所有微博的爬虫,还能断网续爬那种;而微博用户信息爬虫指的是,根据微博用户 id,抓取用户的阳光信用、性别、地区、学校、公司等信息。
代码全部开源在 WeiboSuperSpider 的 github 仓库地址,功能独立版文件夹下,取名 WeiboUserInfoSpider,
https://github.com/Python3Spiders/WeiboSuperSpider或者点击文末的阅读原文直达源代码文件。
https://weibo.com/u/1764201374https://weibo.com/xiena然后就可以运行这份代码了。
核心代码是根据 uid 获取 userinfo 信息,如下
def getUserInfo(uid):try:uid = int(uid)except:# 说明是 xiena 这样的英文串uid = parseUid(uid)if not uid:return Noneresponse = requests.get(url=f'https://weibo.com/ajax/profile/detail?uid={uid}', headers=headers)resp_json = response.json().get('data', None)if not resp_json:return Nonesunshine_credit = resp_json.get('sunshine_credit', None)if sunshine_credit:sunshine_credit_level = sunshine_credit.get('level', None)else:sunshine_credit_level = Noneeducation = resp_json.get('education', None)if education:school = education.get('school', None)else:school = Nonelocation = resp_json.get('location', None)gender = resp_json.get('gender', None)birthday = resp_json.get('birthday', None)created_at = resp_json.get('created_at', None)description = resp_json.get('description', None)# 我关注的人中有多少人关注 tafollowers = resp_json.get('followers', None)if followers:followers_num = followers.get('total_number', None)else:followers_num = Nonereturn {'sunshine_credit_level': sunshine_credit_level,'school': school,'location': location,'gender': gender,'birthday': birthday,'created_at': created_at,'description': description,'followers_num': followers_num}
def parseUid(uid):response = requests.get(url=f'https://weibo.com/ajax/profile/info?custom={uid}', headers=headers)try:return response.json()['data']['user']['id']except:return None
这样只是单独获取某一个 user 的 info,怎么批量获取呢?比如我们利用 2021 新版微博评论及其子评论爬虫发布 爬取了某一条微博的评论,想要获取这些评论者的所有 userinfo,分析它们的地区分布或者性别比例,下面的代码就是干这个的
def dfAddUserInfo(file_path, user_col, user_info_col='user_info'):'''@params file_path 指定路径@params user_col 指定用户主页链接在那一列, 比如评论csv文件的是 comment_user_link@params user_info_col 指定新加的 userinfo 列名,默认是 user_info'''df = pd.read_csv(file_path)user_info_init_value = 'init'columns = df.columns.values.tolist()if not user_info_col in columns:df[user_info_col] = [user_info_init_value for _ in range(df.shape[0])]for index, row in df.iterrows():print(f' {index+1}/{df.shape[0]} ')if not row.get(user_info_col, user_info_init_value) is user_info_init_value:print('skip')continueuser_link = row[user_col]user_id = user_link[user_link.rindex('/')+1:]user_info = getUserInfo(user_id)print(user_info)if user_info:# 在 user_info 中统一为 user_linkuser_info['user_link'] = user_linkdf.loc[index, user_info_col] = json.dumps(user_info)sleep(1)else:print(user_link)breakdf.to_csv(file_path, index=False, encoding='utf-8-sig')
这个函数会把新加的 user_info 字典以 json 形式加到原来的 csv 中,自动新增一列,列名默认取名 user_info;
评论
