【发布时间】:2017-12-27 20:19:57
【问题描述】:
我需要解析在服务器上存档的数百个 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")
关于如何在不映射驱动器的情况下使其工作的任何想法?
【问题讨论】:
标签: python python-3.x urllib unc urlopen