Skip to main content
 首页 » 编程设计

Python 3.6.3 urlopen 从存储在远程服务器上的 html 文件的 URI 中删除服务器名称

2025年01月19日11langtianya

我需要解析服务器上存档的数百个 HTML 文件。这些文件通过 UNC 访问,然后我使用 pathlib 的 as_uri() 方法将 UNC 路径转换为 ​​URI。

下面示例的完整 UNC 路径:\\dmsupportfs\~images\sandbox\test.html

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
import os, pathlib 
 
source_path = os.path.normpath('//dmsupportfs/~images/sandbox/') + os.sep 
filename = 'test.html' 
 
full_path = source_path + filename 
url = pathlib.Path(full_path).as_uri() 
print('URL -> ' + url) 
url_html = urlopen(url).read() 

所以我传递给 urlopen 的 URI(L) 是:file://dmsupportfs/%7Eimages/sandbox/test.html

我可以将它插入任何网络浏览器并返回页面,但是,当 urlopen 读取页面时,它会忽略/删除 URI 中的服务器名称 (dmsupportfs),因此读取失败,无法找到文件。我假设这是 urlopen 方法处理 URI 的方式,但我在这一点上感到困惑(可能是快速且容易解决的事情......抱歉,对 Python 有点陌生)。如果我将 UNC 位置映射到一个驱动器号,然后使用映射的驱动器号而不是 UNC 路径,这将毫无问题地工作。不过,我不想依赖映射驱动器来完成此操作。有什么建议吗?

下面是上述代码的输出,显示了错误:

Traceback (most recent call last): 
  File "C:\Anaconda3\lib\urllib\request.py", line 1474, in open_local_file 
    stats = os.stat(localfile) 
FileNotFoundError: [WinError 3] The system cannot find the path specified: '\\~images\\sandbox\\test.html' 
 
During handling of the above exception, another exception occurred: 
 
Traceback (most recent call last): 
  File "url_test.py", line 10, in <module> 
    url_html = urlopen(url).read() 
  File "C:\Anaconda3\lib\urllib\request.py", line 223, in urlopen 
    return opener.open(url, data, timeout) 
  File "C:\Anaconda3\lib\urllib\request.py", line 526, in open 
    response = self._open(req, data) 
  File "C:\Anaconda3\lib\urllib\request.py", line 544, in _open 
    '_open', req) 
  File "C:\Anaconda3\lib\urllib\request.py", line 504, in _call_chain 
    result = func(*args) 
  File "C:\Anaconda3\lib\urllib\request.py", line 1452, in file_open 
    return self.open_local_file(req) 
  File "C:\Anaconda3\lib\urllib\request.py", line 1491, in open_local_file 
    raise URLError(exp) 
urllib.error.URLError: <urlopen error [WinError 3] The system cannot find the path specified: '\\~images\\sandbox\\test.html'> 

更新:因此,通过挖掘上面的回溯和实际方法,我发现了这一点,它基本上告诉我我正在尝试对 file://URI 做什么,但它不适用于远程服务器。

def file_open(self, req): 
    url = req.selector 
    if url[:2] == '//' and url[2:3] != '/' and (req.host and 
            req.host != 'localhost'): 
        if not req.host in self.get_names(): 
            raise URLError("file:// scheme is supported only on localhost") 

关于如何在不映射驱动器的情况下使它工作的任何想法?

请您参考如下方法:

所以我替换了这个:

url = pathlib.Path(full_path).as_uri()     
url_html = urlopen(url).read() 

用这个:

with open(full_path) as url_html 

并且能够将其传递给 BeautifulSoup 并根据需要进行解析...