python3.6.3 urlopen从存储在远程服务器上的html文件的URI中删除服务器名

2024-09-29 19:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要解析成百上千的HTML文件,这些文件都是在服务器上存档的。这些文件是通过UNC访问的,然后我使用pathlib的as_uri()方法将UNC路径转换为as uri。在

完整的UNC路径,例如:\\dmsupportfs\~images\sandbox\测试.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)是:文件://dmsupportfs/%7Eimages/sandbox/test.html在

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

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

^{pr2}$

更新:所以,通过上面的回溯和实际的方法,我发现了这个,这实际上告诉我,我试图用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")

有什么想法可以让它在不映射驱动器的情况下工作吗?在


Tags: 文件path方法服务器urlhtmlasuri
1条回答
网友
1楼 · 发布于 2024-09-29 19:31:49

所以我替换了这个:

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

有了这个:

^{pr2}$

并能够将其传递到BeautifulGroup并根据需要进行解析。。。在

相关问题 更多 >

    热门问题