diff --git a/README.md b/README.md index cb29fa0..dd7c50b 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,14 @@ pip install git+git://github.com/lzjun567/zhihu-api --upgrade >>> zhihu.send_message("你好,问候2", user_slug="xiaoxiaodouzi") ``` +**关注用户和被关注用户** + +``` +>>> zhihu.follows("高日日") +{"following": 30, + "followers": 4} +``` + **关注用户** ``` >>> zhihu.follow(user_slug="xiaoxiaodouzi") diff --git a/zhihu/models/__init__.py b/zhihu/models/__init__.py index cbd9907..83e80f7 100644 --- a/zhihu/models/__init__.py +++ b/zhihu/models/__init__.py @@ -120,3 +120,25 @@ def _execute(self, method="post", url=None, data=None, data_type=RequestDataType else: r = getattr(self._session, method)(url, data=data, **kwargs) return r + def _get_token(self, Name=None, Headers=settings.HEADERS): + assert type(Name) == str, "name的类型必须为字符串形式" + """ + 根据用户名,获取最相关的用户的token。 + :return: token + >>> _get_token(Name="高日日") + >>> 返回/people/gao-ri-ri-78 + """ + url = 'https://www.zhihu.com/search?type=people&q={}'.format(Name) + data = requests.get(url, headers=Headers) + soup = BeautifulSoup(data.text, 'lxml') + yonghu = soup.select('a[class="name-link author-link"]') + pattern = '(?:[\S\s]*?)' + token = None + for i in yonghu: + i = str(i) + mat = re.findall(pattern, i) + token = mat + if token[0]: + break + + return token[0] diff --git a/zhihu/models/common.py b/zhihu/models/common.py index 5256edf..0c6545b 100644 --- a/zhihu/models/common.py +++ b/zhihu/models/common.py @@ -106,3 +106,37 @@ def unfollow(self, user_slug=None, profile_url=None, **kwargs): return response.json() else: raise ZhihuError("操作失败:%s" % response.text) + + def follows(self, user_name=None): + """ + 用户所关注人数,被关注的人数 + :param user_slug: + :param profile_url: + :return: {"follower_count": int} + + >>> follows(user_name = "高日日") + """ + if not user_name: + raise ZhihuError("至少指定一个关键字参数") + + user_slug = self._get_token(user_name) + + response = requests.get(URL.user_followed_number(user_slug), headers={'User-Agent': + 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36' + }) + if response.ok: + soup = BeautifulSoup(response.text, 'lxml') + init_data_renshu = soup.select('div[class="NumberBoard-value"]') + + dicts = dict() + counts = 0 + for i in init_data_renshu: + if counts < 1: + dicts["following"] = str(i.get_text()) + else: + dicts["followers"] = str(i.get_text()) + counts += 1 + + print(dicts) + else: + raise ZhihuError("操作失败:%s" % response.text) diff --git a/zhihu/url.py b/zhihu/url.py index 831462f..cb6223a 100644 --- a/zhihu/url.py +++ b/zhihu/url.py @@ -45,7 +45,12 @@ def profile(user_slug): @staticmethod def follow_people(user_slug): return URL.host + "/api/v4/members/{user_slug}/followers".format(user_slug=user_slug) - + + # 用户关注页面 + @staticmethod + def user_followed_number(slug): + return URL.host + "{slug}/following".format(slug=slug) + # 赞同/反对/中立 @staticmethod def vote_up(answer_id):