如何等待网页加载后再打开另一个选项卡

2024-04-20 06:59:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了这个小python脚本,可以在早上自动打开我需要的网站,看一看

所需模块

import webbrowser

打开网站

`webbrowser.get('firefox').open_new_tab('https://www.netflix.com')
webbrowser.get('firefox').open_new_tab('https://www.facebook.com')
webbrowser.get('firefox').open_new_tab('https://www.udemy.com') `

我不知道如何等到网页加载后再打开下一个(在另一个选项卡中),有什么帮助吗


Tags: 模块httpsimport脚本comnewgetfacebook
1条回答
网友
1楼 · 发布于 2024-04-20 06:59:29

您可以采用How to wait for the page to fully load using webbrowser method?中提到的方法,手动检查页面中的某个元素

另一个选项是import time并在打开每个选项卡time.sleep(5)后调用它,该选项卡在运行下一行代码之前等待5秒

import webbrowser
from time import sleep

links = ['https://www.netflix.com', 'https://www.facebook.com', 'https://www.udemy.com']

for link in links:
    webbrowser.get('firefox').open_new_tab(link)
    sleep(5)

Selenium实现:

注意:此实现在多个窗口中打开URL,而不是在单个窗口和多个选项卡中打开URL

我将使用chrome驱动程序,您可以在https://chromedriver.chromium.org/downloads安装该驱动程序

import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("detach", True) #this is just to keep the windows open even after the script is done running.

urls = ['https://www.netflix.com', 'https://www.facebook.com', 'https://www.udemy.com']

def open_url(url):
  driver = webdriver.Chrome(executable_path=os.path.abspath('chromedriver'), chrome_options=chrome_options)
  # I've assumed the chromedriver is installed in the same directory as the script. If not, mention the path to the chromedriver executable here.
  driver.get(url) 

for url in urls:
  open_url(url)

相关问题 更多 >