mirror of
https://github.com/NanmiCoder/MediaCrawler.git
synced 2026-04-21 19:27:40 +08:00
feat: 快手关键词搜索存储CSV完成
This commit is contained in:
@@ -31,13 +31,6 @@ class KuaiShouClient:
|
||||
self.cookie_dict = cookie_dict
|
||||
self.graphql = KuaiShouGraphQL()
|
||||
|
||||
async def _pre_headers(self, url: str, data=None):
|
||||
self.headers = {
|
||||
"cookie":"kpf=PC_WEB; clientid=3; did=web_6e79b79fdeac627f5cf52f08cab4e6bd; kpn=KUAISHOU_VISION",
|
||||
"content-type":"application/json"
|
||||
}
|
||||
return self.headers
|
||||
|
||||
async def request(self, method, url, **kwargs) -> Dict:
|
||||
async with httpx.AsyncClient(proxies=self.proxies) as client:
|
||||
response = await client.request(
|
||||
@@ -55,8 +48,7 @@ class KuaiShouClient:
|
||||
if isinstance(params, dict):
|
||||
final_uri = (f"{uri}?"
|
||||
f"{urlencode(params)}")
|
||||
headers = await self._pre_headers(final_uri)
|
||||
return await self.request(method="GET", url=f"{self._host}{final_uri}", headers=headers)
|
||||
return await self.request(method="GET", url=f"{self._host}{final_uri}", headers=self.headers)
|
||||
|
||||
async def post(self, uri: str, data: dict) -> Dict:
|
||||
json_str = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
|
||||
@@ -81,12 +73,12 @@ class KuaiShouClient:
|
||||
|
||||
async def search_info_by_keyword(self, keyword: str, pcursor: str):
|
||||
"""
|
||||
KuaiShou Web Search API
|
||||
KuaiShou web search api
|
||||
:param keyword: search keyword
|
||||
:param pcursor: limite page curson
|
||||
:return:
|
||||
"""
|
||||
params = {
|
||||
post_data = {
|
||||
"operationName": "visionSearchPhoto",
|
||||
"variables": {
|
||||
"keyword": keyword,
|
||||
@@ -95,8 +87,21 @@ class KuaiShouClient:
|
||||
},
|
||||
"query": self.graphql.get("search_query")
|
||||
}
|
||||
return await self.post("", params)
|
||||
return await self.post("", post_data)
|
||||
|
||||
|
||||
async def get_video_info(self, video_id: str) -> Dict:
|
||||
pass
|
||||
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)
|
||||
|
||||
@@ -10,6 +10,7 @@ from base.base_crawler import AbstractCrawler
|
||||
from base.proxy_account_pool import AccountPool
|
||||
from tools import utils
|
||||
from var import crawler_type_var
|
||||
from models import kuaishou
|
||||
|
||||
from .client import KuaiShouClient
|
||||
from .login import KuaishouLogin
|
||||
@@ -91,42 +92,38 @@ class KuaishouCrawler(AbstractCrawler):
|
||||
if not videos_res:
|
||||
utils.logger.error(f"search info by keyword:{keyword} not found data")
|
||||
continue
|
||||
vision_search_photo = videos_res.get("visionSearchPhoto")
|
||||
utils.logger.info(f"videos_res:{videos_res}")
|
||||
semaphore = asyncio.Semaphore(config.MAX_CONCURRENCY_NUM)
|
||||
task_list = [
|
||||
self.get_video_detail(feed_item.get("photo", {}).get("id"), semaphore)
|
||||
for feed_item in vision_search_photo.get("feeds", {})
|
||||
]
|
||||
video_details = await asyncio.gather(*task_list)
|
||||
for video_detail in video_details:
|
||||
if video_detail is not None:
|
||||
video_id_list.append(video_detail.get("id"))
|
||||
page += 1
|
||||
utils.logger.info(f"Video details: {video_details}")
|
||||
await self.batch_get_note_comments(video_id_list)
|
||||
|
||||
await asyncio.Event().wait()
|
||||
vision_search_photo: Dict = videos_res.get("visionSearchPhoto")
|
||||
if vision_search_photo.get("result") != 1:
|
||||
utils.logger.error(f"search info by keyword:{keyword} not found data ")
|
||||
continue
|
||||
|
||||
for video_detail in vision_search_photo.get("feeds"):
|
||||
video_id_list.append(video_detail.get("photo", {}).get("id"))
|
||||
await kuaishou.update_kuaishou_video(video_item=video_detail)
|
||||
|
||||
# batch fetch video comments
|
||||
page += 1
|
||||
await self.batch_get_video_comments(video_id_list)
|
||||
|
||||
async def get_specified_notes(self):
|
||||
pass
|
||||
|
||||
async def batch_get_note_comments(self, video_id_list: List[str]):
|
||||
pass
|
||||
async def batch_get_video_comments(self, video_id_list: List[str]):
|
||||
utils.logger.info(f"[batch_get_video_comments] video ids:{video_id_list}")
|
||||
|
||||
async def get_video_detail(self, ):
|
||||
pass
|
||||
|
||||
async def get_video_detail(self, video_id: str, semaphore: asyncio.Semaphore) -> Optional[Dict]:
|
||||
"""Get note detail"""
|
||||
async def get_video_info_task(self, video_id: str, semaphore: asyncio.Semaphore) -> Optional[Dict]:
|
||||
"""Get video detail task"""
|
||||
async with semaphore:
|
||||
try:
|
||||
return await self.ks_client.get_video_info(video_id)
|
||||
result = await self.ks_client.get_video_info(video_id)
|
||||
utils.logger.info(f"Get video_id:{video_id} info result: {result} ...")
|
||||
return result
|
||||
except DataFetchError as ex:
|
||||
utils.logger.error(f"Get note detail error: {ex}")
|
||||
utils.logger.error(f"Get video detail error: {ex}")
|
||||
return None
|
||||
except KeyError as ex:
|
||||
utils.logger.error(f"have not fund note detail note_id:{note_id}, err: {ex}")
|
||||
utils.logger.error(f"have not fund note detail video_id:{video_id}, err: {ex}")
|
||||
return None
|
||||
|
||||
def create_proxy_info(self) -> Tuple[Optional[str], Optional[Dict], Optional[str]]:
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
query visionVideoDetail($photoId: String, $type: String, $page: String, $webPageArea: String) {
|
||||
visionVideoDetail(photoId: $photoId, type: $type, page: $page, webPageArea: $webPageArea) {
|
||||
status
|
||||
type
|
||||
author {
|
||||
id
|
||||
name
|
||||
following
|
||||
headerUrl
|
||||
__typename
|
||||
}
|
||||
photo {
|
||||
id
|
||||
duration
|
||||
caption
|
||||
likeCount
|
||||
realLikeCount
|
||||
coverUrl
|
||||
photoUrl
|
||||
liked
|
||||
timestamp
|
||||
expTag
|
||||
llsid
|
||||
viewCount
|
||||
videoRatio
|
||||
stereoType
|
||||
musicBlocked
|
||||
manifest {
|
||||
mediaType
|
||||
businessType
|
||||
version
|
||||
adaptationSet {
|
||||
id
|
||||
duration
|
||||
representation {
|
||||
id
|
||||
defaultSelect
|
||||
backupUrl
|
||||
codecs
|
||||
url
|
||||
height
|
||||
width
|
||||
avgBitrate
|
||||
maxBitrate
|
||||
m3u8Slice
|
||||
qualityType
|
||||
qualityLabel
|
||||
frameRate
|
||||
featureP2sp
|
||||
hidden
|
||||
disableAdaptive
|
||||
__typename
|
||||
}
|
||||
__typename
|
||||
}
|
||||
__typename
|
||||
}
|
||||
manifestH265
|
||||
photoH265Url
|
||||
coronaCropManifest
|
||||
coronaCropManifestH265
|
||||
croppedPhotoH265Url
|
||||
croppedPhotoUrl
|
||||
videoResource
|
||||
__typename
|
||||
}
|
||||
tags {
|
||||
type
|
||||
name
|
||||
__typename
|
||||
}
|
||||
commentLimit {
|
||||
canAddComment
|
||||
__typename
|
||||
}
|
||||
llsid
|
||||
danmakuSwitch
|
||||
__typename
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,16 @@ class KuaishouLogin(AbstractLogin):
|
||||
self.cookie_str = cookie_str
|
||||
|
||||
async def begin(self):
|
||||
pass
|
||||
"""Start login xiaohongshu"""
|
||||
utils.logger.info("Begin login kuaishou ...")
|
||||
if self.login_type == "qrcode":
|
||||
await self.login_by_qrcode()
|
||||
elif self.login_type == "phone":
|
||||
await self.login_by_mobile()
|
||||
elif self.login_type == "cookie":
|
||||
await self.login_by_cookies()
|
||||
else:
|
||||
raise ValueError("Invalid Login Type Currently only supported qrcode or phone or cookie ...")
|
||||
|
||||
async def login_by_qrcode(self):
|
||||
pass
|
||||
@@ -37,4 +46,11 @@ class KuaishouLogin(AbstractLogin):
|
||||
pass
|
||||
|
||||
async def login_by_cookies(self):
|
||||
pass
|
||||
utils.logger.info("Begin login kuaishou by cookie ...")
|
||||
for key, value in utils.convert_str_cookie_to_dict(self.cookie_str).items():
|
||||
await self.browser_context.add_cookies([{
|
||||
'name': key,
|
||||
'value': value,
|
||||
'domain': ".douyin.com",
|
||||
'path': "/"
|
||||
}])
|
||||
|
||||
Reference in New Issue
Block a user