Python 打开本地文件适用于 urllib 但不适用于 urllib2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20558587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:43:50  来源:igfitidea点击:

Opening Local File Works with urllib but not with urllib2

pythonurllib2urllib

提问by Jason Brooks

I'm trying to open a local file using urllib2. How can I go about doing this? When I try the following line with urllib:

我正在尝试使用 urllib2 打开本地文件。我该怎么做呢?当我使用 urllib 尝试以下行时:

resp = urllib.urlopen(url)

it works correctly, but when I switch it to:

它工作正常,但是当我切换到:

resp = urllib2.urlopen(url)

I get:

我得到:

ValueError: unknown url type: /path/to/file

where that file definitely does exit.

该文件肯定会退出。

Thanks!

谢谢!

采纳答案by John La Rooy

Just put "file://"in front of the path

就放在"file://"小路前面

>>> import urllib2
>>> urllib2.urlopen("file:///etc/debian_version").read()
'wheezy/sid\n'

回答by Wubao Li

In urllib.urlopen method: If the URL parameter does not have a scheme identifier, it will opens a local file. but the urllib2 doesn't behave like this.

在 urllib.urlopen 方法中:如果 URL 参数没有方案标识符,它将打开一个本地文件。但 urllib2 的行为并不像这样。

So, the urllib2 method can't process it.

所以,urllib2 方法无法处理它。

It's always be good to include the 'file://' schema identifier in both of the method call for the url parameter.

在 url 参数的两个方法调用中都包含“file://”模式标识符总是好的。

回答by oba2311

I had the same issue and actually, I just realized that if you download the source of the page, and then open it on chrome your browser will show you the exact local path on the url bar. Good luck!

我遇到了同样的问题,实际上,我刚刚意识到,如果您下载页面的源代码,然后在 chrome 上打开它,您的浏览器将在 url 栏上显示确切的本地路径。祝你好运!