Opening Local File Works with urllib but not with urllib2

梦想的初衷 提交于 2019-11-29 10:56:01

问题


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:

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!


回答1:


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

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



回答2:


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.

So, the urllib2 method can't process it.

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




回答3:


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!



来源:https://stackoverflow.com/questions/20558587/opening-local-file-works-with-urllib-but-not-with-urllib2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!