#!/usr/bin/python
#filename:urllib_test01.py
#import urllib2 # there is no urllib2 in python3.5
import urllib.request
html = urllib.request.urlopen("http://www.baidu.com").read()
#print (html)
def getdata(url):
try :
data=urllib.request.urlopen(url).read()
z_data=data.decode("UTF-8")
print(z_data)
except Exception as e:
print(e)
return
getdata("http://www.baidu.com") #正确的url调用
getdata("https://www.baidui.com/") #错误的url调用
补充一版根据py3的教程学到的例子
#!/usr/bin/python
#filename:test14.py
f = open('test.txt','wb+')
from urllib.request import urlopen
with urlopen('http://www.baidu.com') as response:
for line in response:
#line = line.decode('utf-8')
#print(line)
f.write(line)
f.close