import urllib.request
访问网址,打开网页,方法:
urllib.request.
urlopen
(url,data=None, [timeout, ]*, cafile=None, capath=None,cadefault=False, context=None)
其中url,可以是一个字符串string(也就是网址),也可以是一个Request对象
方法一:
response = urllib.request.urlopen("http://www.baidu.com")
html = response.read()
html = html.dcode("utf-8")/#按照网页代码,整齐显示
print(html)
方法二:
req = urllib.request.Request("http://www.baidu.com")
response = urllib.request.urlopen(req)
html = response.read()
print(html)
方法一,会把网址首先转化为一个对象,也就是方法二,然后,对对象进行访问。
下载一只猫,网址:http://placekitten.com
req = urllib.request.Request("http://placekitten.com/g/500_600")
response = urllib.request.urlopen(req)
cat_img = response.read()
with open('cat_img_500_600.jpg', 'wb') as f:
f.write(cat_img)