ValueError:urllib2中未知的URL类型,但是如果在浏览器中打开该URL则可以 [英] ValueError: unknown url type in urllib2, though the url is fine if opened in a browser

查看:115
本文介绍了ValueError:urllib2中未知的URL类型,但是如果在浏览器中打开该URL则可以的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在尝试在python中使用urllib2下载URL.

Basically, I am trying to download a URL using urllib2 in python.

代码如下:

import urllib2
req = urllib2.Request('www.tattoo-cover.co.uk')
req.add_header('User-agent','Mozilla/5.0')
result = urllib2.urlopen(req)

它输出ValueError,程序在示例中为URL压缩. 当我在浏览器中访问该URL时,效果很好.

it outputs ValueError and the program crushes for the URL in the example. When I access the url in a browser, it works fine.

有什么想法可以解决这个问题吗?

Any ideas how to handle the problem?

更新:

感谢Ben James并发现了问题=>添加'http://'

thanks for Ben James and sth the problem is detected => add 'http://'

现在,问题已得到完善: 是否可以通过某些内置函数自动处理这种情况?或者我必须在后续的字符串连接中进行错误处理?

Now the question is refined: Is it possible to handle such cases automatically with some builtin function or I have to do error handling with subsequent string concatenation?

推荐答案

在没有协议的浏览器中输入URL时,默认为HTTP. urllib2不会为您做这个假设;您需要在其前面加上http://.

When you enter a URL in a browser without the protocol, it defaults to HTTP. urllib2 won't make that assumption for you; you need to prefix it with http://.

这篇关于ValueError:urllib2中未知的URL类型,但是如果在浏览器中打开该URL则可以的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆