title: 微博用户标识详解
date: 2017-09-06 03:15:27
tags: [爬虫]
微博用户标识详解
微博用户id
微博主要用三种手段标注用户:
- 用户昵称: 显示在页面的名字
- 用户名: 系统中用户的名字
- 用户Id: 系统中用户的ID编号
其中用户昵称是可以修改的, 剩下两个不可修改.
比方说吾爱破解论坛
这个微博用户(http://weibo.com/52pojie),如下图所示:
其昵称为吾爱破解论坛
, 用户名为52pojie
, 用户ID为1780478695
.
无论要抓取的微博链接是以用户昵称还是用户名作为标识的, 我们最后都要将其转化为用户ID, 方便后续的处理.
用户containerId
通过用户的特定containerId
, 我们可以任意一个用户的信息. 比方说其所有发布过的微博和关注好友列表等.
如果只要抓取一个用户所发布的所有微博的话, 则containerId
等于107603+UID
.
比如我们要抓取吾爱破解论坛
的微博,则其对应的containerId
为1076031780478695
.
我们访问以下的链接, 就可以获取到用户的前25条微博.
https://m.weibo.cn/api/container/getIndex?page=1&count=25&containerid=1076031780478695
结果如下所示:
从上面我们可以看到, 用户所发的微博已经全部显示在JSON文件之中了, 我们可以根据自己的需求获取到相应的内容.
- 用户昵称 screen_name
- 用户ID user.id
- 所发图片 pics
- ...
各种Id相互转换的代码
下面的contianerId
指用户微博页面的contianerId
uid转contianerId
/**
* uid转contianerId
* @author yanximin
* */
static String uidToContainerId(String uid){
if(uid==null)
throw new IllegalArgumentException("uid is null");
return 107603+uid;
}
昵称转contianerId
/**
* 昵称转contianerId
* @author yanximin
* @throws IOException
* @throws ClientProtocolException
* */
static String nicknameToContainerId(String nickname) throws ClientProtocolException, IOException{
String url = "http://m.weibo.com/n/"+nickname;
HttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
HttpResponse response = httpClient.execute(post);
post.abort();
if(response.getStatusLine().getStatusCode()==302){
String cid = response.getLastHeader("Location").getValue().substring(27);
return "107603" + cid;
}
return null;
}
用户名转contianerId
/**
* 用户名转contianerId
* @author yanximin
* @throws IOException
* @throws ClientProtocolException
* */
static String usernameToContainerId(String name) throws ClientProtocolException, IOException{
String url = "https://weibo.cn/"+name;
HttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
get.setHeader("User-Agent", USER_AGENT);
HttpResponse response = httpClient.execute(get);
String ret = EntityUtils.toString(response.getEntity(), "utf-8");
Pattern pattern = Pattern.compile("href=\"/([\\d]*?)/info\"");
Matcher matcher = pattern.matcher(ret);
while(matcher.find()){
return "107603" + matcher.group(1);
}
return null;
}