前不久邮箱收到一封邮件,告知我微信下公众号再不使用就被冻结。才想起我去年申请过公众号。于是乎准备好好运营下公众号,可是没有粉丝,然后我想起之前自己也是通过B站视频下的评论才了解到一些公众号或者网站。那我也可以通过B站引流啊。想法已经有了,如何做呢?考虑到B站密码登陆以及接口参数不好破解,只能通过selenium来模拟评论操作了。使用前提是要先通过谷歌浏览器登陆B站然后关闭谷歌浏览器,同时通过参数user_data_dir来指定谷歌用户的数据目录,就可以实现下次浏览器打开的时候自动登陆。
代码效果
代码如下
[block]
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time,random
class BiliBili():
def __init__(self,keyword=None,sentences=None,config={}):
"""
初始化
"""
if isinstance(sentences,str):
self.sentences=[sentences]
elif isinstance(sentences,list):
self.sentences=sentences
else:
self.sentences=["到此一游"]
self.scroll_js = "arguments[0].scrollIntoView();"
self.url = 'https://bilibili.com'
self.config= {"headless":True,"dev":True,"user_data_dir":None,"can_comment":False}
self.config.update(config)
self.keyword=keyword
options = webdriver.ChromeOptions()
options.headless=self.config["headless"]
if self.config["user_data_dir"]:
options.add_argument(self.config["user_data_dir"])
self.config["can_comment"]=True
# 设置为开发者模式,避免被识别
options.add_experimental_option('excludeSwitches',['enable-automation'])
self.browser = webdriver.Chrome(options=options)
self.browser.get(self.url)
# 浏览器最大化
self.browser.maximize_window()
self.wait = WebDriverWait(self.browser,10,0.2)
def search(self):
search_input = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="nav_searchform"]/input')))
search_input.send_keys(self.keyword)
search_button = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="nav_searchform"]/div/button')))
search_button.click()
def go_for_video_list(self):
# 切换窗口
self.switch_window()
print(self.browser.title)
try:
a_list=self.wait.until(EC.presence_of_all_elements_located((By.XPATH,'//a[@class="title"]')),message="不存在视频链接")
time.sleep(2)
for a in a_list:
self.go_for_video_detail(a)
# 切换窗口
self.switch_window()
if self.config["dev"]:
break
# 滑动滚动条到指定的元素
# 翻页
next_button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'next')),message="不存在下一次按钮")
# self.browser.execute_script(self.scroll_js, next_button)
next_button.click()
self.go_for_video_list()
except TimeoutException as e:
print(e)
self.browser.quit()
def switch_window(self):
# 切换窗口
self.browser.switch_to.window(self.browser.window_handles[-1])
def go_for_video_detail(self,a):
a.click()
# 切换到当前窗口
self.switch_window()
print(self.browser.title)
comment = self.wait.until(EC.presence_of_element_located((By.ID, 'comment')),message="不存在评论区域")
# 滑动滚动条到指定的元素
self.browser.execute_script(self.scroll_js,comment)
time.sleep(3)
if self.config["can_comment"]:
try:
textarea = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//textarea[@class="ipt-txt"]')),message="不存在评论框")[0]
button = self.wait.until(EC.presence_of_all_elements_located((By.XPATH, '//button[@class="comment-submit"]')),message="不存在提交按钮")[0]
textarea.send_keys(random.choice(self.sentences))
button.click()
except TimeoutException as e:
print(e)
time.sleep(3)
# 关闭当前窗口
self.browser.close()
if __name__ == '__main__':
config = {"headless": False, "dev": False, "user_data_dir":r"--user-data-dir=C:\\Users\\童\\AppData\\Local\\Google\\Chrome\\User Data" }
test = BiliBili(keyword="django博客",sentences=sentences,config=config)
test.search()
test.go_for_video_list()
| 参数 | 描述 |
| headless | 为True开启浏览器,为False表示关闭浏览器 |
| dev | 为True表示开发模式不会去依次打开所有的视频详情页,只打开一个用来测试 |
| user_data_dir | 这里用来填写你的google用户数据目录。 |
| sentences | 表示评论的语句,支持一个或者是一个列表,如下所示,会随机选取作为评论内容 |
| keyword | 表示搜索关键词 |
[/block]