Python3中请问下列语句有错误么?

#!/usr/bin/python
import urllib.request
import urllib.error

try:
response = urllib.request.urlopen(‘https://www.baidu.com’,timeout=2)
html = response.read().decode(‘utf-8’)
print(html)
except urllib.error.HTTPError as e:
print(‘error’)
Python3中请问下列语句有错误么?


14 回复

看似没有错误


我无法理解你的问题

没缩进

复制的时候有缩进,发布的时候没有了

<br>#!/usr/bin/python <br>
哪里用 python3 了?

试了下应该是 error 的类型错了

#!/usr/bin/python
import urllib.request
import urllib.error

try:
response = urllib.request.urlopen(‘https://www.baidu.com’,timeout=2)
html = response.read().decode(‘utf-8’)
print(html)
except:
print(‘error’)

打印的结果如下:
<html>
<head>
<script>
location.replace(location.href.replace(“https://”,“http://”));
</script>
</head>
<body>
<noscript><meta http-equiv=“refresh” content=“0;url=http://www.baidu.com/”></noscript>
</body>
</html>

有些发行版默认就是 3

#!/usr/bin/env python3

支持楼上,用 env

<br>import urllib.request<br>import urllib.error<br><br>try:<br> response = urllib.request.urlopen('<a target="_blank" href="https://www.baidu.com" rel="nofollow noopener">https://www.baidu.com</a>',timeout=2)<br> html = response.read().decode('utf-8')<br> print(html)<br>except urllib.error.HTTPError as e:<br> print('error')<br>
是没问题的。
输出的 html 也正常

不算是错误,万一人家系统 python 默认版本就是 3 呢?

这个不合规。python3 的可执行文件不能叫 python,只能叫 python3

回到顶部