使用Python在Windows 10中创建可调用Chrome打开的URL快捷方式
Python生成Chrome打开链接的桌面快捷方式实现方案
该功能完全可以通过Python实现,不同操作系统的快捷方式生成逻辑不同,以下是分平台的实现方法:
前置准备
- 确认本地Chrome浏览器的实际安装路径,各系统默认路径参考:
- Windows:
C:\Program Files\Google\Chrome\Application\chrome.exe - macOS:
/Applications/Google Chrome.app/Contents/MacOS/Google Chrome - Linux:
/usr/bin/google-chrome
- Windows:
- 将你爬虫抓取到的链接整理为
(快捷方式名称, 对应URL)的元组列表
Windows平台实现
Windows平台可以直接生成.url格式的标准互联网快捷方式,双击即可调用浏览器打开,也可以选择生成.bat脚本强制指定用Chrome打开:
生成.url快捷方式代码
import os # 配置区域 chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe" # 替换为你爬虫输出的链接列表 url_list = [ ("示例站点1", "https://example.com"), ("示例站点2", "https://example2.com") ] # 获取系统桌面路径 desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") for name, url in url_list: # 过滤文件名非法字符,避免生成失败 safe_name = "".join([c for c in name if c not in r'\/:*?"<>|']) shortcut_file = os.path.join(desktop_path, f"{safe_name}.url") with open(shortcut_file, "w", encoding="utf-8") as f: f.write("[InternetShortcut]\n") f.write(f"URL={url}\n") f.write(f"IconFile={chrome_path}\n") f.write("IconIndex=0\n") print(f"已生成快捷方式:{shortcut_file}")
强制调用Chrome打开的实现
如果需要强制用Chrome打开而非系统默认浏览器,可以生成.bat脚本,替换上述代码的写入逻辑即可:
# 替换上述代码中with open部分的内容 shortcut_file = os.path.join(desktop_path, f"{safe_name}.bat") with open(shortcut_file, "w", encoding="gbk") as f: f.write(f'start "" "{chrome_path}" "{url}"')
macOS/Linux平台实现
macOS和Linux平台使用.desktop格式的快捷方式,实现代码如下:
import os # 配置区域,Linux将chrome_path改为/usr/bin/google-chrome chrome_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" # 替换为你爬虫输出的链接列表 url_list = [ ("示例站点1", "https://example.com"), ("示例站点2", "https://example2.com") ] desktop_path = os.path.join(os.path.expanduser("~"), "Desktop") for name, url in url_list: safe_name = "".join([c for c in name if c not in r'\/:*?"<>|']) shortcut_file = os.path.join(desktop_path, f"{safe_name}.desktop") with open(shortcut_file, "w", encoding="utf-8") as f: f.write("[Desktop Entry]\n") f.write("Type=Application\n") f.write(f"Name={name}\n") f.write(f"Exec=\"{chrome_path}\" \"{url}\"\n") f.write("Icon=google-chrome\n") f.write("Terminal=false\n") # 给快捷方式赋予执行权限 os.chmod(shortcut_file, 0o755) print(f"已生成快捷方式:{shortcut_file}")
注意事项
- 若Chrome的安装路径非默认路径,替换配置区的
chrome_path为实际路径即可 - 爬虫抓取的链接可以直接对接进
url_list,无需额外处理 - Windows下生成bat文件时编码选择gbk可避免中文乱码问题
内容的提问来源于stack exchange,提问作者Nitish Kumar
相关产品推荐
相关产品推荐

