【问题标题】:urllib.error.URLError: <urlopen error unknown url type: 'https>urllib.error.URLError:<urlopen 错误未知 url 类型:'https>
【发布时间】:2015-01-22 19:30:03
【问题描述】:

(Python 3.4.2) 当我在脚本中运行 'urllib.request.urlopen(url)' 时出现了一个奇怪的错误。如果我直接在 Python 解释器中运行它,它可以正常工作,但当我通过 bash shell (Linux) 在脚本内部运行它时就不行了。

我猜它与“url”字符串有关,可能是因为我正在通过“string.join”方法创建字符串。

import urllib.request
url = "".join((baseurl, other_string, midurl, query))
response = urllib.request.urlopen(url)

“url”字符串打印完美,但是当我尝试创建“response”字符串时,我得到以下输出:

File "./script.py", line 124, in <module>
    response = urllib.request.urlopen(url)
  File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 455, in open
    response = self._open(req, data)
  File "/usr/lib/python3.4/urllib/request.py", line 478, in _open
    'unknown_open', req)
  File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.4/urllib/request.py", line 1244, in unknown_open
    raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: 'https>

Python 是在我的计算机上使用 SSL 支持编译的(这些命令在 Python 解释器中完美运行)。

我还尝试使用“repr(url)”和“str(url)”来包装“url”字符串。我也试过这个:

url = "".join(("'", baseurl, other_string, midurl, query, "'"))

有人知道怎么回事吗?

-----编辑-----
我想到了。我的网址中有一个“:”,我猜 urllib 不喜欢这样。我用“%3A”替换了它,现在它可以工作了。

【问题讨论】:

标签: python-3.x urllib


【解决方案1】:

您应该使用urllib.parse.urlencode()urllib.parse.urljoin() 等函数来构造url,而不是手动连接字符串。它将处理 : -> %3A 转换,例如:

>>> import urllib.parse
>>> urllib.parse.quote(':')
'%3A'

【讨论】:

    【解决方案2】:

    我想通了。我的网址中有一个:,而urllib 不能使用该字符。我用%3A 替换了它,现在它可以工作了。 Web 浏览器通常会自动将: 转换为%3A,但urllib 需要先转换。

    【讨论】:

      【解决方案3】:

      如果你不安装可能是因为openssl-devel。

      yum list installed|grep openssl
      

      安装它并在make后重试。

      sudo yum install openssl-devel
      ./configure
      make
      

      【讨论】:

        【解决方案4】:

        遇到错误的人 ValueError: unknown url type: 'http 要么 ValueError: unknown url type: b'http

        同时使用urllib.request.Request 打开如下网址 'http://localhost/simple_form/insert.php'

        只需将localhost 更改为127.0.0.1

        看起来 Request 方法在 url 中寻找 domain.something

        【讨论】:

          猜你喜欢
          • 2019-07-22
          • 2015-04-07
          • 2018-12-04
          • 2020-10-15
          • 2012-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多