You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在macOS上用Python关闭浏览器标签页的技术需求与问题

Fixing Tab Closure & Hourly Automation for Your Spareroom Listing Refreshes

Got it, let's tackle this problem head-on. The webbrowser module is great for quick one-off opens, but it doesn't give you any control over tabs or windows after launching them—so we'll switch to Selenium, a tool built for full browser automation, which lets us open, interact with, and close tabs exactly how we need. We'll also set up reliable hourly scheduling.

Step 1: Install Required Tools

First, install the dependencies we'll need:

pip install selenium schedule

For browsers:

  • Brave: Uses the same driver as Chrome. Download the matching ChromeDriver version for your Brave release (make sure it's in your system PATH or specify its path in the code).
  • Safari: Enable "Remote Automation" first: Go to Safari > Preferences > Advanced, check "Show Develop menu in menu bar", then go to Develop > Allow Remote Automation.

Step 2: Full Automation Code

This code will handle both your listing groups, close tabs immediately after refresh, and run every hour. We'll use Brave for all listings to keep things simple (you can split back to Safari for nums2 if needed—see the notes below).

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import schedule
import time

def refresh_all_listings():
    # Configure Brave Browser
    brave_options = Options()
    # Update this path to match your Brave installation (Windows path example: "C:/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe")
    brave_options.binary_location = "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"
    driver = webdriver.Chrome(options=brave_options)

    # Base URL parts
    base_start = "https://www.spareroom.co.uk/flatshare/advert_renew.pl?advert_id="
    base_end = "&flatshare_type=offered"

    # Combine all listing IDs into one list (split into two groups if you still want separate browsers)
    all_listing_ids = [
        '13549393', '13292512', '13787806', '13787662', '11924089',
        '12755839', '5467930', '3844433', '12950809', '9187090',
        '11834794', '8017675', '5154283', '12418570', '12459514'
    ]

    # Open a blank initial tab to anchor our session
    driver.get("about:blank")

    for listing_id in all_listing_ids:
        full_url = f"{base_start}{listing_id}{base_end}"
        
        # Open a new tab
        driver.execute_script("window.open('');")
        # Switch to the new tab
        driver.switch_to.window(driver.window_handles[-1])
        # Load the refresh URL
        driver.get(full_url)
        # Wait 2 seconds to ensure the refresh action completes
        time.sleep(2)
        # Close the current tab
        driver.close()
        # Switch back to our initial blank tab
        driver.switch_to.window(driver.window_handles[0])

    # Close the entire browser session when done
    driver.quit()

# Schedule the job to run every hour
schedule.every().hour.do(refresh_all_listings)

# Run the first refresh immediately, then start the scheduling loop
refresh_all_listings()
while True:
    schedule.run_pending()
    # Check for pending jobs every 60 seconds to avoid high CPU usage
    time.sleep(60)

If You Still Want to Use Safari for nums2:

Modify the refresh_all_listings function to split the groups:

def refresh_all_listings():
    # Handle nums in Brave first
    brave_options = Options()
    brave_options.binary_location = "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"
    brave_driver = webdriver.Chrome(options=brave_options)
    brave_driver.get("about:blank")

    nums = ['13549393', '13292512', '13787806', '13787662', '11924089']
    base_start = "https://www.spareroom.co.uk/flatshare/advert_renew.pl?advert_id="
    base_end = "&flatshare_type=offered"

    for listing_id in nums:
        full_url = f"{base_start}{listing_id}{base_end}"
        brave_driver.execute_script("window.open('');")
        brave_driver.switch_to.window(brave_driver.window_handles[-1])
        brave_driver.get(full_url)
        time.sleep(2)
        brave_driver.close()
        brave_driver.switch_to.window(brave_driver.window_handles[0])
    
    brave_driver.quit()

    # Now handle nums2 in Safari
    safari_driver = webdriver.Safari()
    safari_driver.get("about:blank")
    nums2 = ['12755839', '5467930', '3844433', '12950809', '9187090', '11834794', '8017675', '5154283', '12418570', '12459514']
    
    for listing_id in nums2:
        full_url = f"{base_start}{listing_id}{base_end}"
        safari_driver.execute_script("window.open('');")
        safari_driver.switch_to.window(safari_driver.window_handles[-1])
        safari_driver.get(full_url)
        time.sleep(2)
        safari_driver.close()
        safari_driver.switch_to.window(safari_driver.window_handles[0])
    
    safari_driver.quit()

Key Notes

  • Tab Control: We use window.open() to create new tabs, switch_to.window() to navigate between them, and close() to shut the active tab after the refresh completes.
  • Browser Cleanup: driver.quit() ensures the entire browser process is closed, no leftover windows or tabs.
  • Scheduling: The schedule library handles hourly runs reliably. For a more system-level solution, you could use macOS Launchd or Windows Task Scheduler instead, but this code keeps everything self-contained.

内容的提问来源于stack exchange,提问作者C00P3RR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:04:43