2023-11-23 15:13:54 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import asyncio
|
|
|
|
import json
|
2023-11-26 13:43:39 +00:00
|
|
|
from typing import Any, Callable, Dict, Optional
|
2023-11-23 16:04:33 +00:00
|
|
|
from urllib.parse import urlencode
|
2023-11-23 15:13:54 +00:00
|
|
|
|
|
|
|
import httpx
|
|
|
|
from playwright.async_api import BrowserContext, Page
|
|
|
|
|
2023-12-13 15:53:12 +00:00
|
|
|
import config
|
2023-11-23 15:13:54 +00:00
|
|
|
from tools import utils
|
|
|
|
|
|
|
|
from .exception import DataFetchError, IPBlockError
|
2023-11-26 13:43:39 +00:00
|
|
|
from .graphql import KuaiShouGraphQL
|
2023-11-23 15:13:54 +00:00
|
|
|
|
|
|
|
|
2023-11-24 16:02:33 +00:00
|
|
|
class KuaiShouClient:
|
2023-11-23 15:13:54 +00:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
timeout=10,
|
|
|
|
proxies=None,
|
|
|
|
*,
|
|
|
|
headers: Dict[str, str],
|
|
|
|
playwright_page: Page,
|
|
|
|
cookie_dict: Dict[str, str],
|
|
|
|
):
|
|
|
|
self.proxies = proxies
|
|
|
|
self.timeout = timeout
|
|
|
|
self.headers = headers
|
2023-11-24 16:02:33 +00:00
|
|
|
self._host = "https://www.kuaishou.com/graphql"
|
2023-11-23 15:13:54 +00:00
|
|
|
self.playwright_page = playwright_page
|
|
|
|
self.cookie_dict = cookie_dict
|
2023-11-24 16:02:33 +00:00
|
|
|
self.graphql = KuaiShouGraphQL()
|
2023-11-23 15:13:54 +00:00
|
|
|
|
2023-11-26 13:43:39 +00:00
|
|
|
async def request(self, method, url, **kwargs) -> Any:
|
2023-11-23 15:13:54 +00:00
|
|
|
async with httpx.AsyncClient(proxies=self.proxies) as client:
|
|
|
|
response = await client.request(
|
|
|
|
method, url, timeout=self.timeout,
|
|
|
|
**kwargs
|
|
|
|
)
|
|
|
|
data: Dict = response.json()
|
2023-11-24 16:02:33 +00:00
|
|
|
if data.get("errors"):
|
|
|
|
raise DataFetchError(data.get("errors", "unkonw error"))
|
2023-11-23 15:13:54 +00:00
|
|
|
else:
|
2023-11-24 16:02:33 +00:00
|
|
|
return data.get("data", {})
|
2023-11-23 15:13:54 +00:00
|
|
|
|
|
|
|
async def get(self, uri: str, params=None) -> Dict:
|
|
|
|
final_uri = uri
|
|
|
|
if isinstance(params, dict):
|
|
|
|
final_uri = (f"{uri}?"
|
2023-11-23 16:04:33 +00:00
|
|
|
f"{urlencode(params)}")
|
2023-11-25 17:05:52 +00:00
|
|
|
return await self.request(method="GET", url=f"{self._host}{final_uri}", headers=self.headers)
|
2023-11-23 15:13:54 +00:00
|
|
|
|
|
|
|
async def post(self, uri: str, data: dict) -> Dict:
|
|
|
|
json_str = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
|
|
|
|
return await self.request(method="POST", url=f"{self._host}{uri}",
|
2023-11-24 16:02:33 +00:00
|
|
|
data=json_str, headers=self.headers)
|
2023-11-23 15:13:54 +00:00
|
|
|
|
2023-12-05 14:47:36 +00:00
|
|
|
@staticmethod
|
|
|
|
async def pong() -> bool:
|
2023-11-23 15:13:54 +00:00
|
|
|
"""get a note to check if login state is ok"""
|
2023-11-23 16:04:33 +00:00
|
|
|
utils.logger.info("Begin pong kuaishou...")
|
2023-11-23 15:13:54 +00:00
|
|
|
ping_flag = False
|
|
|
|
try:
|
|
|
|
pass
|
|
|
|
except Exception as e:
|
2023-11-23 16:04:33 +00:00
|
|
|
utils.logger.error(f"Pong kuaishou failed: {e}, and try to login again...")
|
2023-11-23 15:13:54 +00:00
|
|
|
ping_flag = False
|
|
|
|
return ping_flag
|
2023-11-23 16:04:33 +00:00
|
|
|
|
|
|
|
async def update_cookies(self, browser_context: BrowserContext):
|
|
|
|
cookie_str, cookie_dict = utils.convert_cookies(await browser_context.cookies())
|
|
|
|
self.headers["Cookie"] = cookie_str
|
2023-11-24 16:02:33 +00:00
|
|
|
self.cookie_dict = cookie_dict
|
|
|
|
|
|
|
|
async def search_info_by_keyword(self, keyword: str, pcursor: str):
|
|
|
|
"""
|
2023-11-25 17:05:52 +00:00
|
|
|
KuaiShou web search api
|
2023-11-24 16:02:33 +00:00
|
|
|
:param keyword: search keyword
|
|
|
|
:param pcursor: limite page curson
|
|
|
|
:return:
|
|
|
|
"""
|
2023-11-25 17:05:52 +00:00
|
|
|
post_data = {
|
2023-11-24 16:02:33 +00:00
|
|
|
"operationName": "visionSearchPhoto",
|
|
|
|
"variables": {
|
|
|
|
"keyword": keyword,
|
|
|
|
"pcursor": pcursor,
|
|
|
|
"page": "search"
|
|
|
|
},
|
|
|
|
"query": self.graphql.get("search_query")
|
|
|
|
}
|
2023-11-25 17:05:52 +00:00
|
|
|
return await self.post("", post_data)
|
2023-11-24 16:02:33 +00:00
|
|
|
|
2023-11-25 17:05:52 +00:00
|
|
|
async def get_video_info(self, photo_id: str) -> Dict:
|
|
|
|
"""
|
|
|
|
Kuaishou web video detail api
|
|
|
|
:param photo_id:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
post_data = {
|
|
|
|
"operationName": "visionVideoDetail",
|
|
|
|
"variables": {
|
|
|
|
"photoId": photo_id,
|
|
|
|
"page": "search"
|
|
|
|
},
|
|
|
|
"query": self.graphql.get("video_detail")
|
|
|
|
}
|
|
|
|
return await self.post("", post_data)
|
2023-11-26 13:43:39 +00:00
|
|
|
|
|
|
|
async def get_video_comments(self, photo_id: str, pcursor: str = "") -> Dict:
|
|
|
|
"""get video comments
|
|
|
|
:param photo_id: photo id you want to fetch
|
|
|
|
:param pcursor: last you get pcursor, defaults to ""
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
post_data = {
|
|
|
|
"operationName": "commentListQuery",
|
|
|
|
"variables": {
|
|
|
|
"photoId": photo_id,
|
|
|
|
"pcursor": pcursor
|
|
|
|
},
|
|
|
|
"query": self.graphql.get("comment_list")
|
|
|
|
|
|
|
|
}
|
|
|
|
return await self.post("", post_data)
|
|
|
|
|
|
|
|
async def get_video_all_comments(self, photo_id: str, crawl_interval: float = 1.0, is_fetch_sub_comments=False,
|
2023-12-13 15:53:12 +00:00
|
|
|
callback: Optional[Callable] = None):
|
2023-11-26 13:43:39 +00:00
|
|
|
"""
|
|
|
|
get video all comments include sub comments
|
|
|
|
:param photo_id:
|
|
|
|
:param crawl_interval:
|
|
|
|
:param is_fetch_sub_comments:
|
|
|
|
:param callback:
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
|
|
|
|
result = []
|
|
|
|
pcursor = ""
|
2023-12-13 15:53:12 +00:00
|
|
|
count = 0 # 计数器,记录已获取的评论数量
|
|
|
|
|
|
|
|
while pcursor != "no_more" and (
|
|
|
|
config.MAX_COMMENTS_PER_POST == 0 or count < config.MAX_COMMENTS_PER_POST):
|
2023-11-26 13:43:39 +00:00
|
|
|
comments_res = await self.get_video_comments(photo_id, pcursor)
|
|
|
|
vision_commen_list = comments_res.get("visionCommentList", {})
|
|
|
|
pcursor = vision_commen_list.get("pcursor", "")
|
|
|
|
comments = vision_commen_list.get("rootComments", [])
|
|
|
|
|
2023-12-13 15:53:12 +00:00
|
|
|
filtered_comments = [] # 存储经过关键词筛选后的评论
|
|
|
|
|
|
|
|
for comment in comments:
|
|
|
|
content = comment.get("content", "")
|
|
|
|
|
|
|
|
if not config.COMMENT_KEYWORDS or any(keyword in content for keyword in config.COMMENT_KEYWORDS):
|
|
|
|
filtered_comments.append(comment)
|
|
|
|
|
|
|
|
count += 1
|
|
|
|
if config.MAX_COMMENTS_PER_POST != 0 and count >= config.MAX_COMMENTS_PER_POST:
|
|
|
|
break
|
|
|
|
|
2023-11-26 13:43:39 +00:00
|
|
|
if callback: # 如果有回调函数,就执行回调函数
|
2023-12-13 15:53:12 +00:00
|
|
|
await callback(photo_id, filtered_comments)
|
2023-11-26 13:43:39 +00:00
|
|
|
|
2023-12-13 15:53:12 +00:00
|
|
|
result.extend(filtered_comments)
|
2023-11-26 13:43:39 +00:00
|
|
|
await asyncio.sleep(crawl_interval)
|
|
|
|
if not is_fetch_sub_comments:
|
|
|
|
continue
|
|
|
|
# todo handle get sub comments
|
|
|
|
return result
|