Python如何访问互联网
urllib包
URL的一般格式为(带方括号[]的为可选项): protocol://hostname
URL由三部分组成:
- 第一部分时协议 :http,https,ftp,file,ed2k..
- 第二部分是存放资源的服务器域名系统或IP地址
- 第三部分是资源具体的地址
import urllib.request #导入包中的request模块
response = urllib.request.urlopen("http://www.baidu.com")#从服务器上获取网页
#获取到的网页是一个对象
#读取对象
html = response.read() #读取出的是二进制的字符串
#解码二进制字符串
html = html.decode("utf-8")
print(html)
爬取图片
import urllib.request
response = urllib.request.urlopen("http://placekitten.com/g/500/600")
img = response.read()
with open('下载的图片2.jpg' , 'wb') as f:
f.write(img)