Skip to content

Commit

Permalink
feat: B站爬虫搜索关键词实现
Browse files Browse the repository at this point in the history
  • Loading branch information
NanmiCoder committed Dec 3, 2023
1 parent 5aeee93 commit a90b411
Show file tree
Hide file tree
Showing 6 changed files with 303 additions and 17 deletions.
35 changes: 23 additions & 12 deletions media_platform/bilibili/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from .help import BilibiliSign
from .exception import DataFetchError
from .field import OrderType


class BilibiliClient:
Expand Down Expand Up @@ -53,7 +54,7 @@ async def pre_request_data(self, req_data: Dict) -> Dict:
:param req_data:
:return:
"""
img_key, sub_key = self.get_wbi_keys()
img_key, sub_key = await self.get_wbi_keys()
return BilibiliSign(img_key, sub_key).sign(req_data)

async def get_wbi_keys(self) -> tuple[str, str]:
Expand All @@ -62,9 +63,10 @@ async def get_wbi_keys(self) -> tuple[str, str]:
:return:
"""
local_storage = await self.playwright_page.evaluate("() => window.localStorage")
wbi_img_urls = local_storage.get("wbi_img_urls", "")
img_url, sub_url = wbi_img_urls.split("-")
if not img_url or not sub_url:
wbi_img_urls = local_storage.get("wbi_img_urls", "") or local_storage.get("wbi_img_url") + "-" + local_storage.get("wbi_sub_url")
if wbi_img_urls and "-" in wbi_img_urls:
img_url, sub_url = wbi_img_urls.split("-")
else:
resp = await self.request(method="GET", url=self._host + "/x/web-interface/nav")
img_url: str = resp['wbi_img']['img_url']
sub_url: str = resp['wbi_img']['sub_url']
Expand All @@ -74,14 +76,14 @@ async def get_wbi_keys(self) -> tuple[str, str]:

async def get(self, uri: str, params=None) -> Dict:
final_uri = uri
params = self.pre_request_data(params)
params = await self.pre_request_data(params)
if isinstance(params, dict):
final_uri = (f"{uri}?"
f"{urlencode(params)}")
return await self.request(method="GET", url=f"{self._host}{final_uri}", headers=self.headers)

async def post(self, uri: str, data: dict) -> Dict:
data = self.pre_request_data(data)
data = await self.pre_request_data(data)
json_str = json.dumps(data, separators=(',', ':'), ensure_ascii=False)
return await self.request(method="POST", url=f"{self._host}{uri}",
data=json_str, headers=self.headers)
Expand All @@ -102,21 +104,30 @@ async def update_cookies(self, browser_context: BrowserContext):
self.headers["Cookie"] = cookie_str
self.cookie_dict = cookie_dict

async def search_info_by_keyword(self, keyword: str, pcursor: str):
async def search_video_by_keyword(self, keyword: str, page: int = 1, page_size: int = 20,
order: OrderType = OrderType.DEFAULT):
"""
KuaiShou web search api
:param keyword: search keyword
:param pcursor: limite page curson
:param keyword: 搜索关键词
:param page: 分页参数具体第几页
:param page_size: 每一页参数的数量
:param order: 搜索结果排序,默认位综合排序
:return:
"""
uri = "/x/web-interface/wbi/search/type"
post_data = {
"search_type": "video",
"keyword": keyword,
"page": page,
"page_size": page_size,
"order": order.value
}
return await self.post("", post_data)
return await self.get(uri, post_data)

async def get_video_info(self, photo_id: str) -> Dict:
async def get_video_info(self, video_id: str) -> Dict:
"""
Kuaishou web video detail api
:param photo_id:
:param video_id:
:return:
"""
post_data = {
Expand Down
135 changes: 133 additions & 2 deletions media_platform/bilibili/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@

import config
from base.base_crawler import AbstractCrawler
from models import kuaishou
from models import bilibili
from proxy.proxy_account_pool import AccountPool
from tools import utils
from var import comment_tasks_var, crawler_type_var


from .client import BilibiliClient
from .exception import DataFetchError
from .field import OrderType
from .login import BilibiliLogin


Expand All @@ -45,7 +46,137 @@ def init_config(self, platform: str, login_type: str, account_pool: AccountPool,
self.crawler_type = crawler_type

async def start(self):
account_phone, playwright_proxy, httpx_proxy = self.create_proxy_info()
async with async_playwright() as playwright:
# Launch a browser context.
chromium = playwright.chromium
self.browser_context = await self.launch_browser(
chromium,
playwright_proxy,
self.user_agent,
headless=config.HEADLESS
)
# stealth.min.js is a js script to prevent the website from detecting the crawler.
await self.browser_context.add_init_script(path="libs/stealth.min.js")
self.context_page = await self.browser_context.new_page()
await self.context_page.goto(self.index_url)

# Create a client to interact with the xiaohongshu website.
self.bili_client = await self.create_bilibili_client(httpx_proxy)
if not await self.bili_client.pong():
login_obj = BilibiliLogin(
login_type=self.login_type,
login_phone=account_phone,
browser_context=self.browser_context,
context_page=self.context_page,
cookie_str=config.COOKIES
)
await login_obj.begin()
await self.bili_client.update_cookies(browser_context=self.browser_context)

crawler_type_var.set(self.crawler_type)
if self.crawler_type == "search":
# Search for video and retrieve their comment information.
await self.search()
elif self.crawler_type == "detail":
# Get the information and comments of the specified post
await self.get_specified_videos()
else:
pass
utils.logger.info("Bilibili Crawler finished ...")
pass

async def search(self):
"""
search bilibili video with keywords
:return:
"""
utils.logger.info("Begin search bilibli keywords")
bili_limit_count = 20 # bilibili limit page fixed value
for keyword in config.KEYWORDS.split(","):
utils.logger.info(f"Current search keyword: {keyword}")
page = 1
while page * bili_limit_count <= config.CRAWLER_MAX_NOTES_COUNT:
video_id_list: List[str] = []
videos_res = await self.bili_client.search_video_by_keyword(
keyword=keyword,
page=page,
page_size=bili_limit_count,
order=OrderType.DEFAULT,
)
video_list: List[Dict] = videos_res.get("result")
for video_item in video_list:
video_id_list.append(video_item.get("id"))
await bilibili.update_bilibili_video(video_item)
page += 1

async def get_specified_videos(self):
"""
get specified videos info
:return:
"""
pass

async def create_bilibili_client(self, httpx_proxy: Optional[str]) -> BilibiliClient:
"""Create xhs client"""
utils.logger.info("Begin create xiaohongshu API client ...")
cookie_str, cookie_dict = utils.convert_cookies(await self.browser_context.cookies())
bilibili_client_obj = BilibiliClient(
proxies=httpx_proxy,
headers={
"User-Agent": self.user_agent,
"Cookie": cookie_str,
"Origin": "https://www.bilibili.com",
"Referer": "https://www.bilibili.com",
"Content-Type": "application/json;charset=UTF-8"
},
playwright_page=self.context_page,
cookie_dict=cookie_dict,
)
return bilibili_client_obj

def create_proxy_info(self) -> Tuple[Optional[str], Optional[Dict], Optional[str]]:
"""Create proxy info for playwright and httpx"""
# phone: 13012345671 ip_proxy: 111.122.xx.xx1:8888
phone, ip_proxy = self.account_pool.get_account()
if not config.ENABLE_IP_PROXY:
return phone, None, None
utils.logger.info("Begin proxy info for playwright and httpx ...")
playwright_proxy = {
"server": f"{config.IP_PROXY_PROTOCOL}{ip_proxy}",
"username": config.IP_PROXY_USER,
"password": config.IP_PROXY_PASSWORD,
}
httpx_proxy = f"{config.IP_PROXY_PROTOCOL}{config.IP_PROXY_USER}:{config.IP_PROXY_PASSWORD}@{ip_proxy}"
return phone, playwright_proxy, httpx_proxy

async def launch_browser(
self,
chromium: BrowserType,
playwright_proxy: Optional[Dict],
user_agent: Optional[str],
headless: bool = True
) -> BrowserContext:
"""Launch browser and create browser context"""
utils.logger.info("Begin create browser context ...")
if config.SAVE_LOGIN_STATE:
# feat issue #14
# we will save login state to avoid login every time
user_data_dir = os.path.join(os.getcwd(), "browser_data",
config.USER_DATA_DIR % self.platform) # type: ignore
browser_context = await chromium.launch_persistent_context(
user_data_dir=user_data_dir,
accept_downloads=True,
headless=headless,
proxy=playwright_proxy, # type: ignore
viewport={"width": 1920, "height": 1080},
user_agent=user_agent
)
return browser_context
else:
browser = await chromium.launch(headless=headless, proxy=playwright_proxy) # type: ignore
browser_context = await browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent=user_agent
)
return browser_context
23 changes: 23 additions & 0 deletions media_platform/bilibili/field.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
# @Author : [email protected]
# @Time : 2023/12/3 16:20
# @Desc :

from enum import Enum


class OrderType(Enum):
# 综合排序
DEFAULT = ""

# 最多点击
MOST_CLICK = "click"

# 最新发布
LAST_PUBLISH = "pubdate"

# 最多弹幕
MOST_DANMU = "dm"

# 最多收藏
MOST_MARK = "stow"
4 changes: 2 additions & 2 deletions media_platform/bilibili/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ def sign(self, req_data: Dict) -> Dict:
salt = self.get_salt()
wbi_sign = md5((query + salt).encode()).hexdigest() # 计算 w_rid
req_data['w_rid'] = wbi_sign
# print(urllib.parse.urlencode(req_data))
print(urllib.parse.urlencode(req_data))
return req_data


if __name__ == '__main__':
_img_key = "7cd084941338484aae1ad9425b84077c"
_sub_key = "4932caff0ff746eab6f01bf08b70ac45"
_search_url = "category_id=&search_type=video&ad_resource=5654&__refresh__=true&_extra=&context=&page=1&page_size=42&order=click&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&keyword=python&qv_id=OQ8f2qtgYdBV1UoEnqXUNUl8LEDAdzsD&source_tag=3&gaia_vtoken=&dynamic_offset=0&web_location=1430654"
_search_url = "__refresh__=true&_extra=&ad_resource=5654&category_id=&context=&dynamic_offset=0&from_source=&from_spmid=333.337&gaia_vtoken=&highlight=1&keyword=python&order=click&page=1&page_size=20&platform=pc&qv_id=OQ8f2qtgYdBV1UoEnqXUNUl8LEDAdzsD&search_type=video&single_column=0&source_tag=3&web_location=1430654"
_req_data = dict()
for params in _search_url.split("&"):
kvalues = params.split("=")
Expand Down
29 changes: 28 additions & 1 deletion media_platform/bilibili/login.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
# -*- coding: utf-8 -*-
# @Author : [email protected]
# @Time : 2023/12/2 18:44
# @Desc :
# @Desc : bilibli登录类实现

import asyncio
import functools
import sys
from typing import Optional

import redis
from playwright.async_api import BrowserContext, Page
from tenacity import (RetryError, retry, retry_if_result, stop_after_attempt,
wait_fixed)

import config
from base.base_crawler import AbstractLogin
from tools import utils
from base.base_crawler import AbstractLogin


class BilibiliLogin(AbstractLogin):
def __init__(self,
login_type: str,
browser_context: BrowserContext,
context_page: Page,
login_phone: Optional[str] = "",
cookie_str: str = ""
):
self.login_type = login_type
self.browser_context = browser_context
self.context_page = context_page
self.login_phone = login_phone
self.cookie_str = cookie_str

async def begin(self):
pass

Expand Down
Loading

0 comments on commit a90b411

Please sign in to comment.