コード例 #1
0
ファイル: question.py プロジェクト: xianfuxing/zhihu-api
 def follow_question(self, **kwargs):
     """关注某问题"""
     r = self._execute(url=URL.follow_question(self.id), **kwargs)
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #2
0
 def unfollow_question(self, **kwargs):
     """取消关注某问题"""
     r = self._execute(method="delete",
                       url=URL.unfollow_question(self.id),
                       **kwargs)
     if r.ok:
         return {"is_following": False}
コード例 #3
0
ファイル: account.py プロジェクト: xsongx/zhihu-api
 def _login_with_email(self, email, password, **kwargs):
     data = {'email': email,
             'password': password,
             '_xsrf': self._get_xsrf(**kwargs),
             "captcha": self._get_captcha(**kwargs),
             'remember_me': 'true'}
     return self._login_execute(url=URL.email_login(), data=data, **kwargs)
コード例 #4
0
ファイル: common.py プロジェクト: tomguluson92/zhihu-api
    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"]')
            lst0 = ["关注人数"]
            lst1 = ["关注者"]
            for i in init_data_renshu:
                if len(lst0) < 2:
                    lst0.append(str(i.get_text()))
                else:
                    lst1.append(str(i.get_text()))
            print(','.join(lst0))
            print(','.join(lst1))

        else:
            raise ZhihuError("操作失败:%s" % response.text)
コード例 #5
0
    def _get_captcha(self, _type="login"):
        response = self.get(URL.api_captcha())
        r = re.findall('"show_captcha":(\w+)', response.text)
        if r[0] == 'false':
            return ''
        else:
            response = self.put(
                'https://www.zhihu.com/api/v3/oauth/captcha?lang=en',
                headers=self.headers)
            show_captcha = json.loads(response.text)['img_base64']
            with open('captcha.jpg', 'wb') as f:
                f.write(base64.b64decode(show_captcha))
            # 调用系统图片预览工具
            if platform.system() == 'Darwin':
                subprocess.call(['open', 'captcha.jpg'])
            elif platform.system() == 'Linux':
                subprocess.call(['xdg-open', 'captcha.jpg'])
            else:
                os.startfile('captcha.jpg')
            captcha = input("输入验证码:")
            data = {"input_text": captcha}

            response = self.post(
                'https://www.zhihu.com/api/v3/oauth/captcha?lang=en',
                headers=self.headers,
                data=data)
            return captcha
コード例 #6
0
ファイル: account.py プロジェクト: cczhong11/zhihu-api
 def _login_api(self, account, password):
     time_stamp = str(int((time.time() * 1000)))
     _xsrf, _ = self._get_xsrf_dc0(
         url="https://www.zhihu.com/signup?next=%2F")
     self.headers.update({
         "content-type": "application/x-www-form-urlencoded",
         "authorization": "oauth c3cef7c66a1843f8b3a9e6a1e3160e20",  # 固定值
         "X-Xsrftoken": _xsrf
     })
     captcha = self._get_captcha()
     self.headers.update({'x-zse-83': '3_1.1', })  # 不带会有"请求参数异常,请升级客户端后重试"
     
     data = {
         "client_id": "c3cef7c66a1843f8b3a9e6a1e3160e20",
         "grant_type": "password",
         "timestamp": time_stamp,
         "source": "com.zhihu.web",
         "password": password,
         "username": quote(account),
         "lang": "en",
         "ref_source": "homepage",
         "utm_source": "",
         "signature": self._get_signature(time_stamp),
         'captcha': captcha
     }
     return self._login_execute(url=URL.api_login(), data=data)
コード例 #7
0
    def _get_captcha(self, _type="login"):
        response = self.get(URL.api_captcha())
        r = re.findall('"show_captcha":(\w+)', response.text)
        if r[0] == 'false':
            return ''
        else:
            response = self.put(
                'https://www.zhihu.com/api/v3/oauth/captcha?lang=en', headers=self.headers)
            show_captcha = json.loads(response.text)['img_base64']
            with open('captcha.jpg', 'wb') as f:
                f.write(base64.b64decode(show_captcha))
            # 调用系统图片预览工具
            if platform.system() == 'Darwin':
                subprocess.call(['open', 'captcha.jpg'])
            elif platform.system() == 'Linux':
                subprocess.call(['xdg-open', 'captcha.jpg'])
            else:
                os.startfile('captcha.jpg')
            captcha = input("输入验证码:")
            data = {"input_text": captcha}
            # data = json.dumps(data)

            # 要进行加密
            path = os.path.join(os.path.split(
                os.path.realpath(__file__))[0], 'encrypt.js')
            with open(path, "r") as f:
                js = execjs.compile(f.read())
                print(data)
                # data = js.call('Q', urlencode(data))
            response = self.post('https://www.zhihu.com/api/v3/oauth/captcha?lang=en',
                                 headers=self.headers, data=data)
            print("看这里 输入验证码返回值")
            print(response.json())
            return captcha
コード例 #8
0
ファイル: zhihu.py プロジェクト: abbychau/zhihu-api
    def profile(self, user_slug=None, user_url=None):
        """
        获取用户信息
        :param user_slug : 用户的个性域名
        :param user_url: 用户主页地址

        :return:dict
                {'avatar_url_template': 'https://pic1.zhimg.com/v2-ca13758626bd7367febde704c66249ec_{size}.jpg',
                'name': '我是小号',
                'is_advertiser': False,
                'url': 'http://www.zhihu.com/api/v4/people/1da75b85900e00adb072e91c56fd9149',
                'gender': -1,
                'user_type': 'people',
                'url_token': 'xiaoxiaodouzi',
                'headline': '',
                'avatar_url': 'https://pic1.zhimg.com/v2-ca13758626bd7367febde704c66249ec_is.jpg',
                'is_org': False, '
                type': 'people',
                'badge': [],
                'id': '1da75b85900e00adb072e91c56fd9149'}


        >>> user(profile_url = "https://www.zhihu.com/people/xiaoxiaodouzi")
        >>> user(user_slug = "xiaoxiaodouzi")

        """
        response = self._execute(method="get", url=URL.profile(user_slug))
        if response.ok:
            return response.json()
        else:
            raise ZhihuError("操作失败:%s" % response.text)
コード例 #9
0
ファイル: zhihu.py プロジェクト: abbychau/zhihu-api
    def send_message(self,
                     content,
                     user_id=None,
                     user_url=None,
                     user_slug=None):
        """
        给指定的用户发私信
        :param content 私信内容
        :param user_id 用户id
        :param user_url: 用户主页地址
        :param user_slug : 用户的个性域名
        Usege::

          >>> send_message(profile_url = "https://www.zhihu.com/people/xiaoxiaodouzi")
          >>> send_message(user_slug = "xiaoxiaodouzi")
          >>> send_message(user_id = "1da75b85900e00adb072e91c56fd9149")
        """

        assert any((user_id, user_url, user_slug)), "至少指定一个关键字参数"

        if not user_id:
            user_id = self._user_id(user_slug=user_slug, user_url=user_url)
        data = {"type": "common", "content": content, "receiver_hash": user_id}
        response = self._execute(method='post', url=URL.message(), json=data)
        return response
コード例 #10
0
    def send_message(self,
                     content,
                     user_id=None,
                     profile_url=None,
                     user_slug=None,
                     **kwargs):
        """
        给指定的用户发私信
        :param content 私信内容
        :param user_id 用户id
        :param profile_url :用户主页地址
        :param user_slug : 用户的个性域名

        >>> send_message(profile_url = "https://www.zhihu.com/people/xiaoxiaodouzi")
        >>> send_message(user_slug = "xiaoxiaodouzi")
        >>> send_message(user_id = "1da75b85900e00adb072e91c56fd9149")
        """
        if not any([user_id, profile_url, user_slug]):
            raise ZhihuError("至少指定一个关键字参数")

        if user_id is None:
            user_slug = self._user_slug(
                profile_url) if user_slug is None else user_slug
            user_id = self._user_id(user_slug)

        data = {"type": "common", "content": content, "receiver_hash": user_id}
        response = self._session.post(URL.message(), json=data, **kwargs)
        if response.ok:
            self.log("发送成功")
        else:
            self.log("发送失败")
        return response.text
コード例 #11
0
 def request(self, data=None, **kwargs):
     url = URL.vote_up(self.id)
     r = self._session.post(url, json=data, **kwargs)
     if r.ok:
         self.log("操作成功")
     else:
         self.log("操作失败")
     return r.text
コード例 #12
0
ファイル: answer.py プロジェクト: zhihaowen/zhihu-api
 def vote_neutral(self, **kwargs):
     """
     中立
     """
     r = self._execute(url=URL.vote_neutral(self.id),
                       data={"type": "neutral"},
                       **kwargs)
     if r.ok:
         return r.json()
コード例 #13
0
ファイル: answer.py プロジェクト: zhihaowen/zhihu-api
 def vote_down(self, **kwargs):
     """
     反对
     """
     r = self._execute(url=URL.vote_down(self.id),
                       data={"type": "down"},
                       **kwargs)
     if r.ok:
         return r.json()
コード例 #14
0
 def nothelp(self, **kwargs):
     """
     没有帮助
     """
     r = self._execute(url=URL.nothelp(self.id), **kwargs)
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #15
0
ファイル: answer.py プロジェクト: zhihaowen/zhihu-api
 def thank_cancel(self, **kwargs):
     """
     感谢取消
     """
     r = self._execute(method="delete",
                       url=URL.thank_cancel(self.id),
                       **kwargs)
     if r.ok:
         return r.json()
コード例 #16
0
ファイル: answer.py プロジェクト: xsongx/zhihu-api
 def thank(self, **kwargs):
     """
     感谢
     """
     r = self._execute(url=URL.thank(self.id), **kwargs)
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #17
0
ファイル: answer.py プロジェクト: xsongx/zhihu-api
 def vote_neutral(self, **kwargs):
     """
     中立
     """
     r = self._execute(url=URL.vote_neutral(self.id), data={"type": "neutral"}, **kwargs)
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #18
0
 def nothelp_cancel(self, **kwargs):
     """
     撤销没有帮助
     """
     r = self._execute(method="delete", url=URL.nothelp_cancel(self.id), **kwargs)
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #19
0
ファイル: account.py プロジェクト: transferXiang/zhihu-api
 def _login_with_phone(self, phone, password, **kwargs):
     data = {
         '_xsrf': self._get_xsrf(),
         'password': password,
         'phone_num': phone,
         "captcha": self._get_captcha(),
         "remeber_me": "true",
     }
     return self._execute(url=URL.phone_login(), data=data, **kwargs)
コード例 #20
0
ファイル: answer.py プロジェクト: zeni18/zhihu-api
 def nothelp(self):
     """
     没有帮助
     """
     r = self._execute(method="delete", url=URL.nothelp(self.id))
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #21
0
ファイル: answer.py プロジェクト: zhihaowen/zhihu-api
 def vote_up(self, **kwargs):
     """
     赞同
     """
     r = self._execute(url=URL.vote_up(self.id),
                       data={"type": "up"},
                       **kwargs)
     if r.ok:
         return r.json()
コード例 #22
0
ファイル: answer.py プロジェクト: zeni18/zhihu-api
 def thank(self):
     """
     感谢
     """
     r = self._execute(method="post", url=URL.thank(self.id))
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #23
0
ファイル: answer.py プロジェクト: zeni18/zhihu-api
 def thank_cancel(self):
     """
     感谢取消
     """
     r = self._execute(method="delete", url=URL.thank_cancel(self.id))
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #24
0
 def unfollow_question(self, **kwargs):
     """取消关注某问题"""
     r = self._execute(method="delete",
                       url=URL.unfollow_question(self.id),
                       **kwargs)
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #25
0
ファイル: base.py プロジェクト: zhenchaom/zhihu-api
 def _get_xsrf(self, url=None):
     """
     获取某个URL页面下的xsrf
     :param url:
     :return: xsrf
     """
     response = self.get(url or URL.index())
     soup = BeautifulSoup(response.content, "lxml")
     xsrf = soup.find('input', attrs={"name": "_xsrf"}).get("value")
     return xsrf
コード例 #26
0
 def _get_xsrf_dc0(self, url=None):
     """
     获取某个URL页面下的xsrf
     :param url:
     :return: xsrf
     """
     response = self.get(url or URL.index())
     xsrf = response.cookies["_xsrf"]
     dc0 = response.cookies["d_c0"]
     return xsrf, dc0
コード例 #27
0
ファイル: answer.py プロジェクト: zeni18/zhihu-api
 def vote_neutral(self, ):
     """
     中立
     """
     r = self._execute(method="post",
                       url=URL.vote_neutral(self.id),
                       json={"type": "neutral"})
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #28
0
ファイル: answer.py プロジェクト: zeni18/zhihu-api
 def vote_down(self):
     """
     反对
     """
     r = self._execute(method="post",
                       url=URL.vote_down(self.id),
                       json={"type": "down"})
     if r.ok:
         return r.json()
     else:
         raise ZhihuError("操作失败:%s" % r.text)
コード例 #29
0
 def _get_xsrf(self, url=None, **kwargs):
     """
     获取某个页面下的xsrf
     :param url:
     :param kwargs:
     :return:
     """
     response = self._session.get(url or URL.index(), **kwargs)
     soup = BeautifulSoup(response.content, "html.parser")
     xsrf = soup.find('input', attrs={"name": "_xsrf"}).get("value")
     return xsrf
コード例 #30
0
    def _get_captcha(self, _type="login", **kwargs):
        r = self._session.get(URL.captcha(_type=_type), **kwargs)
        with open('captcha.jpg', 'wb') as f:
            f.write(r.content)

        if platform.system() == 'Darwin':
            subprocess.call(['open', 'captcha.jpg'])
        elif platform.system() == 'Linux':
            subprocess.call(['xdg-open', 'captcha.jpg'])
        else:
            os.startfile('captcha.jpg')
        captcha = input("输入验证码:")
        return captcha