123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- # coding=utf-8
- import os
- import time
- import requests
- import sys
- from selenium import webdriver
- '''
- 记录日志
- '''
- def print_log(content):
- content = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' ' + content
- print(content)
- logfile = './kwaiLiveCookie.log'
- file = open(logfile, 'a', encoding='utf8')
- file.write(content + '\n')
- # 关闭文件
- file.close()
- class KwaiLiveWebDriver:
- # 初始化方法:设置浏览器驱动
- def __init__(self):
- chrome_driver_path = r'chromedriver.exe'
- option = webdriver.ChromeOptions()
- option.add_argument(r'--user-data-dir=C:\Chrome\Replication3') # 设置成用户自己的数据目录
- option.add_argument(r'--disable-software-rasterizer')
- os.environ["webdriver.chrome.driver"] = chrome_driver_path
- self.browser = webdriver.Chrome(
- executable_path=chrome_driver_path,
- options=option
- )
- '''
- 模拟登录方法
- account:账号
- passwd:密码
- '''
- def openLive(self):
- browser = self.browser
- # chrome浏览器打开快手直播页
- browser.get("https://live.kuaishou.com/u/danshenzaici")
- print_log('打开浏览器,进入快手直播页')
- #
- # browser.implicitly_wait(60) # 隐性等待,最长等30秒
- #
- # enterLive = browser.find_element_by_class_name('enter-live-btn')
- #
- # # 点击进入直播间
- # enterLive.click()
- time.sleep(10)
- # 主播尚未开播,则点击推荐直播
- if "主播尚未开播" in browser.page_source:
- print_log('主播尚未开播:' + browser.current_url)
- previewLive = browser.find_elements_by_class_name('preview-video')
- previewLiveLen = len(previewLive)
- print(previewLiveLen)
- previewLive[previewLiveLen - 1].click()
- time.sleep(10)
- print_log('获取当前链接:' + browser.current_url)
- cookies_list = browser.get_cookies()
- print_log('获取Cookie:')
- # print(cookies_list)
- cookies_str = ''
- for cookie_item in cookies_list:
- cookies_str = cookies_str + cookie_item['name'] + '=' + cookie_item['value'] + '; '
- print_log(cookies_str)
- response = requests.post(
- 'https://ks.wenxingshuju.com/v2/api/kwaiOpen/saveCookie',
- {'cookie': cookies_str}
- )
- print_log('发送Cookie:' + response.text)
- time.sleep(60)
- browser.quit()
- print_log('关闭浏览器')
- print_log('--------------------------------')
- if __name__ == '__main__':
- kwaiLiveWebDriver = KwaiLiveWebDriver()
- try:
- kwaiLiveWebDriver.openLive()
- except Exception as e:
- print_log('抛出异常!' + str(e))
- kwaiLiveWebDriver.browser.quit()
- sys.exit(0)
|