如何让这两个url中的视频都自动播放呢?

进入python终端,交互式运行,输入:

from playwright.sync_api import Playwright, sync_playwright, expect
playwright = sync_playwright().start() 
browser= playwright.firefox.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("some_video_website")

输入账号,密码,二维码,以我目前的实力,无法用程序自动识别二维码,因此手动完成。再输入:


urls = ["url1_some_video_website",
        "url2_some_video_website"]

for url in urls:
    page.goto(url)
    with page.expect_popup() as page1_info:
        #在那个网页结构中,下面成立
        page.get_by_text("play").click()
        page1 = page1_info.value
        page1.get_by_role("img").click()

我的本意是让浏览器自动播放url1,url2,但是我发现这个for循环,仅仅能播放第一个视频,请问,如何修改一下,完成两个视频都自动播放呢?

阅读 1k
2 个回答
from playwright.sync_api import sync_playwright
import time  

def main():
    with sync_playwright() as playwright:
        # 启动浏览器
        browser = playwright.firefox.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()
        
        page.goto("https://some_video_website.com")
        print("请手动完成登录操作(输入账号、密码、二维码等)...")
        time.sleep(30)

        # 视频URL列表
        urls = [
            "https://some_video_website.com/video1",
            "https://some_video_website.com/video2"
        ]

        for idx, url in enumerate(urls, start=1):
            print(f"正在播放第 {idx} 个视频: {url}")
            page.goto(url)
            
            try:
                # 监听弹出窗口
                with page.expect_popup() as popup_info:
                    # 点击“play”按钮
                    page.get_by_text("play").click()
                popup = popup_info.value
                
                # 等待弹出窗口加载完成
                popup.wait_for_load_state("load")
                
                # 点击弹出窗口中的播放按钮(假设是一个图片按钮)
                popup.get_by_role("img").click()
                
                # 可选:等待视频播放一段时间
                time.sleep(10)  # 播放10秒
                
                # 关闭弹出窗口
                popup.close()
                print(f"第 {idx} 个视频播放完成并已关闭弹出窗口。")
            except Exception as e:
                print(f"播放第 {idx} 个视频时出错: {e}")

        # 关闭浏览器
        browser.close()
        print("所有视频已播放完成。")

if __name__ == "__main__":
    main()
from playwright.sync_api import Playwright, sync_playwright, expect

def run(playwright: Playwright) -> None:
    browser = playwright.firefox.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("some_video_website")

    # 手动输入账号、密码和二维码

    urls = ["url1_some_video_website", "url2_some_video_website"]

    for url in urls:
        page.goto(url)
        with page.expect_popup() as page1_info:
            page.get_by_text("play").click()
        page1 = page1_info.value
        page1.get_by_role("img").click()
        page1.close()  # 关闭弹出窗口

    browser.close()

with sync_playwright() as playwright:
    run(playwright)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏