在Python中调用URL时出错

时间:2018-12-28 10:37:15

标签: python ubuntu

我已经在 ubuntu 14 中安装了 python3.7 。以下是我遵循的过程

  1. 下载了 python 3.7
  2. ./configure
  3. sudo make
  4. sudo make install

现在我正在运行以下代码

from urllib.request import urlopen
resp = urlopen('http://github.com')
print(resp.read())

但是它在控制台上出现以下错误:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    resp = urlopen('https://github.com')
  File "/usr/local/lib/python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/lib/python3.7/urllib/request.py", line 525, in open
    response = self._open(req, data)
  File "/usr/local/lib/python3.7/urllib/request.py", line 548, in _open
    'unknown_open', req)
  File "/usr/local/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python3.7/urllib/request.py", line 1387, in unknown_open
    raise URLError('unknown url type: %s' % type)`enter code here`
urllib.error.URLError: <urlopen error unknown url type: https>

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

发生错误的原因是您的Python是在没有SSL支持的情况下配置和构建的,并且当 setTimeout(function() { //your datatable code }, 1000); github.com重定向到http URL时,您会看到以下错误:https

检查您的配置日志,您会看到有关检测到不支持SSL的消息。

解决方案是安装所有必需的依赖项(在本例中为unknown url type: https或类似的东西),并从源头重新配置和重新构建Python。

答案 1 :(得分:0)

尝试通过导入requests.get()库来使用requests函数。 我在python 2.7上运行良好

import requests

r = requests.get('https://www.facebook.com/')
print type(r)
print r.status_code 
print r.headers
print r.headers['content-type']

输出:

    <class 'requests.models.Response'>
    200
    {'X-XSS-Protection': '0', 'X-Content-Type-Options': 'nosniff', 'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'fr=1my64VtKmpcYv2gSs..BcJgcK.TG.AAA.0.0.BcJgcK.AWXA3lHz; expires=Thu, 28-Mar-2019 11:20:42 GMT; Max-Age=7776000; path=/; domain=.facebook.com; secure; httponly, sb=CgcmXH47CJp-Qfmz1uyl_6eC; expires=Sun, 27-Dec-2020 11:20:42 GMT; Max-Age=63072000; path=/; domain=.facebook.com; secure; httponly', 'Strict-Transport-Security': 'max-age=15552000; preload', 'Vary': 'Accept-Encoding', 'X-FB-Debug': 'eP7JRcFDBbaRkLwVBGwHxDrySoaxLgW0z5eCGJibzcznQNszHVs/m0Vhh9v1i6aX5ri+bMmwpbbFnL4fCNNMPQ==', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'private, no-cache, no-store, must-revalidate', 'Date': 'Fri, 28 Dec 2018 11:20:42 GMT', 'X-Frame-Options': 'DENY', 'Content-Type': 'text/html; charset="utf-8"', 'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'}
    text/html; charset="utf-8"