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

Python PermissionError: [Errno 13]权限拒绝问题求助

PermissionError: [Errno 13] 权限拒绝问题解决

环境与问题

Windows 10 + Python 3.12环境下运行下述代码时触发权限拒绝错误,已尝试管理员权限运行、确认目标目录无程序占用且拥有写入权限,问题仍未解决。

代码

import eel
from googleapiclient.discovery import build
import urllib.request
from html.parser import HTMLParser
import os
import pathlib
import webbrowser
import ssl
import shutil

path = "web"
os.makedirs(path, exist_ok=True)

eel.init('web')

@eel.expose
def search(query):
    API_KEY = "xxxxxxxxx"
    CSE_ID = "xxxxxxxx"

    service = build("customsearch", "v1", developerKey=API_KEY)
    response = service.cse().list(q=query, cx=CSE_ID).execute()

    if "items" in response and response["items"]:
        first_result = response["items"][0]

        url = first_result.get("formattedUrl", "")

        class MyHTMLParser(HTMLParser):
            def __init__(self):
                super().__init__()
                self.urls = []

            def handle_starttag(self, tag, attrs):
                if tag in ["script", "link", "img"]:
                    for attr in attrs:
                        if attr[0] in ["src", "href"]:
                            self.urls.append(attr[1])

        ctx = ssl._create_unverified_context()
        res = urllib.request.urlopen(url, context=ctx)
        if res.code == 200:
            html = res.read().decode("utf-8")

            parser = MyHTMLParser()
            parser.feed(html)
            urls = parser.urls

            html_path = pathlib.Path(path) / pathlib.Path(urllib.parse.urlparse(url).path).name
            with open(html_path, "w", encoding="utf-8") as f:
                f.write(html)

            for url in urls:
                if url.startswith("http"):
                    file_url = url
                else:
                    file_url = urllib.request.urljoin(res.url, url)

                file_path = pathlib.Path(path) / pathlib.Path(urllib.parse.unquote(urllib.parse.urlparse(file_url).path)).name
                try:
                    urllib.request.urlretrieve(file_url, file_path)
                except:
                    print(f"Neuspešno preuzimanje fajla: {file_url}")

            return html_path
        else:
            return None
    else:
        return None

input = input(">>> ")
html_path = search(input)
webbrowser.open(str(html_path), new=2)

shutil.rmtree('web')

错误信息

Traceback (most recent call last):
  File "C:\Users\xxxxxxxx\Desktop\xxxxxxxxxxx.py", line 72, in <module>
    html_path = search(input)
                ^^^^^^^^^^^^^
  File "C:\Users\xxxxxxxx\Desktop\xxxxxxxx.py", line 50, in search
    with open(html_path, "w", encoding="utf-8") as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: 'web'

解决方法

问题根源

当目标URL是域名根目录(比如https://example.com/)时,urllib.parse.urlparse(url).path的值为/,对应的pathlib.Path(...).name会是空字符串,导致html_path被解析为web/(即目录)。此时尝试打开目录进行写入操作,就会触发权限拒绝错误。

修复步骤

  1. 确保HTML文件名有效:为解析到的空文件名设置默认值(比如index.html),修改html_path的定义代码:

    parsed_url = urllib.parse.urlparse(url)
    # 若解析出的文件名为空,使用index.html作为默认
    html_file_name = pathlib.Path(parsed_url.path).name or "index.html"
    html_path = pathlib.Path(path) / html_file_name
    
  2. 避免资源文件写入目录:处理静态资源URL时,同样检查文件名是否为空,若为空则跳过或设置默认名:

    for url in urls:
        if url.startswith("http"):
            file_url = url
        else:
            file_url = urllib.request.urljoin(res.url, url)
    
        parsed_file_url = urllib.parse.urlparse(file_url)
        file_name = pathlib.Path(urllib.parse.unquote(parsed_file_url.path)).name
        # 跳过空文件名的资源,防止写入目录
        if not file_name:
            continue
        file_path = pathlib.Path(path) / file_name
        try:
            urllib.request.urlretrieve(file_url, file_path)
        except:
            print(f"Neuspešno preuzimanje fajla: {file_url}")
    
  3. 检查eel目录占用:eel.init('web')会初始化并占用web目录资源,若后续写入操作受此影响,可将eel.init的调用移至search函数内部(如果业务逻辑允许),或者在写入文件前确保eel未锁定目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:43:12