# -*- coding: utf-8 -*-

from time import sleep
from random import randint
import os
os.environ['NO_PROXY'] = 'stackoverflow.com'
import logging
logging.captureWarnings(True)
from DrissionPage import ChromiumPage
import json
import requests
import re
import random
import time
from datetime import datetime, timedelta
from all_connect import ConnectSpider
Con = ConnectSpider()



class TT():
    def __init__(self):
        self.page = ChromiumPage()
        self.headers = {
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'no-cache',
    'content-type': 'application/json; charset=UTF-8',
    'origin': 'https://www.tiktok.com',
    'pragma': 'no-cache',
    'priority': 'u=1, i',
    'referer': 'https://www.tiktok.com/',
    'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'cross-site',
    'sec-fetch-storage-access': 'active',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
}


    def login(self):
        try:

            # 初始化浏览器对象
            self.page = ChromiumPage()
            self.account = "@heartygreet"
            self.page.get(f"https://www.tiktok.com/{self.account}")

            # 等待页面初始加载
            time.sleep(randint(6, 12))

            # 获取当前窗口高度（用于判断是否到底）
            last_height = self.page.run_js('return document.body.scrollHeight')
            scroll_pause_time = random.randint(6,12)
            collected_hrefs = set()  # 用于去重
            page = 1

            while True:
                print(f"正在处理第 {page} 页")
                all_items = []  # 存储所有要插入的数据

                # 提取当前页所有视频项数据
                video_items = self.page.eles('xpath=//div[@data-e2e="user-post-item"]')
                for index, item in enumerate(video_items):
                    try:
                        view_count = item.ele('xpath=.//strong[@data-e2e="video-views"]').text
                        view_href = item.ele('css=.css-1j167yi-DivWrapper a').attr('href')

                        data = {
                            'account': self.account,
                            'view_href': view_href,
                            'view_count': view_count,
                            'page': page,
                            'index': index + 1,
                            'state': 1,
                            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                        }

                        if view_href not in collected_hrefs:
                            collected_hrefs.add(view_href)
                            all_items.append(data)
                            # print(f"第 {index + 1} 个视频: {view_href} 浏览量: {view_count}")

                    except Exception as e:
                        print(f"第 {index + 1} 个视频获取失败: {str(e)}")

                # 保存本页数据
                if all_items:
                    Con.save_tiktok_data(all_items)

                # 滚动到底部
                self.page.scroll.to_bottom()

                # 等待新内容加载
                time.sleep(scroll_pause_time)

                # 计算新的滚动高度
                new_height = self.page.run_js('return document.body.scrollHeight')

                # 如果已经到底了，退出循环
                if new_height == last_height:
                    print("已到达页面底部，停止滚动")
                    break

                last_height = new_height
                page += 1  # 下一页


            # 打开页面
            # self.page.get("https://www.tiktok.com/@heartygreet/video/7481384554343746862")
            # sleep(randint(6, 12))
            # # print(self.page.html)
            #
            #
            # elements = self.page.eles('xpath=//div[contains(@class, "DivActionItemContainer")]//strong')
            # numbers = [ele.text for ele in elements]
            # print(numbers)
            # sleep(randint(3, 4))
            # # print(text)
            # text = self.page.ele('xpath=//span[@class="css-1kcycbd-SpanOtherInfos evv7pft3"]/span[3]').text
            # print(text)
            #
            # sleep(randint(2, 4))



        except Exception as e:
            print(f"出现错误: {e}")
            return False




if __name__ == '__main__':
    ck = TT().login()








