【开放源代码】微博搜索用户爬虫
点击上方 月小水长 并 设为星标,第一时间接收干货推送
超级方便的微博用户信息爬虫 是根据微博用户 Uid 来抓取公开的用户微博信息,但是很多时候,我们可能只知道这个用户的微博名字,并不知道 Uid,本次开放的爬虫就是完成从微博用户名到 Uid 的转换。

该爬虫抓取的接口是 https://s.weibo.com/user,需要该接口下最好是已登录的 cookie。主要抓取逻辑如下,可以像 不写一行,自动生成爬虫代码 文章里说的那样自动生成该部分代码。
def getUidByName(name):# https://s.weibo.com/user?q=%E6%B5%8B%E8%AF%95&Refer=weibo_usercookie = '复制上面接口登录后的 cookie'headers = {'Connection': 'keep-alive','Cache-Control': 'max-age=0','sec-ch-ua-mobile': '?0','sec-ch-ua-platform': '"Windows"','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36','Sec-Fetch-Site': 'same-origin','Sec-Fetch-Mode': 'navigate','Sec-Fetch-User': '?1','Sec-Fetch-Dest': 'document','Referer': 'https://s.weibo.com/weibo?q=%E6%B5%8B%E8%AF%95','Accept-Language': 'zh-CN,zh;q=0.9,en-CN;q=0.8,en;q=0.7,es-MX;q=0.6,es;q=0.5','cookie': cookie}params = {'q': name,'Refer': 'weibo_user',}response = requests.get('https://s.weibo.com/user', headers=headers, params=params)return parseResponse(response)
拿到 response 后稍微解析一下就能拿到 Uid,如果出错或者没有搜索到,Uid 返回 -1
def parseResponse(response):html = etree.HTML(response.text)users = html.xpath('//div[starts-with(@class,"card card-user-b")]/div[@class="info"]/div/a[last()-1]/@href')if len(users) == 0:return -1temp = users[0]uid = temp[temp.rindex('/') + 1:]return uid
类比用户信息爬虫,很自然而然想到需要有批量抓取的需求,所以同时写了个批量处理的逻辑如下:
def dfAddUserLink(file_path, user_name_cloumn, user_link_column='user_link', finish_column='finish'):df = pd.read_csv(file_path)if not finish_column in df.columns.values.tolist():df[finish_column] = [False for _ in range(df.shape[0])]df[user_link_column] = ['' for _ in range(df.shape[0])]df.to_csv(file_path, index=False, encoding='utf-8-sig')consist = 0consist_limit = 3for index, row in df.iterrows():print(f'{index+1}/{df.shape[0]}')if row[finish_column] == True:continueuid = getUidByName(row[user_name_cloumn])if uid == -1:consist += 1if consist >= consist_limit:print('请检查是否需要换 cookie')df.to_csv(file_path, index=False, encoding='utf-8-sig')breakelse:consist = 0user_link = f"https://weibo.com/u/{uid}"print(user_link)df.loc[index, user_link_column] = user_linkdf.loc[index, finish_column] = Trueif index % 10 == 0:df.to_csv(file_path, index=False, encoding='utf-8-sig')
它会自动根据指定路径下的 csv 文件里的用户名抓取用户链接并保存到 csv 中,连续出错三次则需要 check 下是否出错比如 cookie 失效,如果需要抓取的 csv 文件里面行数过多,一次性爬不完也没有关系,每抓 10 个自动保存一次,由于新加了个 finish 标志字段,下次运行会从上次爬到的地方继续。
比如我们有一个 test.csv ,其中用户名信息在 user_name 列,我们可以这样调用。
dfAddUserLink('test.csv', user_name_column='user_name')代码地址在:
https://github.com/Python3Spiders/WeiboSuperSpider/blob/master/%E6%97%A0%20GUI%20%E5%8A%9F%E8%83%BD%E7%8B%AC%E7%AB%8B%E7%89%88/WeiboUserScrapy.py文末 阅读原文 直达。
最后依旧是微博话题爬虫的日常更新,修复了群里朋友提出的若干问题,提升了稳定性。可以去 2021 新版微博话题爬虫发布 获取最新的微博话题爬虫。
评论
