import requests
from bs4 import BeautifulSoup


def get_video_url(page_url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }

    response = requests.get(page_url, headers=headers)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')

        # 在这里分析页面内容，寻找视频链接
        # 这个选择器需要根据实际页面结构来调整
        video_elements = soup.find_all('video')

        for video in video_elements:
            video_src = video.get('src')
            if video_src:
                print("Found video URL:", video_src)
                return video_src

        print("No video URL found, please check the page structure.")
    else:
        print("Failed to retrieve the page, status code:", response.status_code)

    return None


def download_video(video_url, output_path):
    response = requests.get(video_url, stream=True)
    if response.status_code == 200:
        with open(output_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=1024):
                file.write(chunk)
        print(f"Video downloaded successfully and saved as {output_path}")
    else:
        print("Failed to download video, status code:", response.status_code)


# 使用示例
page_url = "https://jx.xmflv.cc/?url=https://v.qq.com/x/cover/x5ul2annjsbcwh8/e00335q391x.html"
video_url = get_video_url(page_url)
if video_url:
    download_video(video_url, "output_video.mp4")