urllib是Python中常用的库之一,库中内置几个模块request(请求)error(错误)parse(URL解析)robotparser(robots.txt解析)我们主要学习request和parse
使用之前别忘了引用模块
import urllib.request,urllib.parserequest里最简单的用法就是直接urlopen
response = urllib.request.urlopen('http://www.xxxx.com') # xxxx.com就是你要访问的网址我常用的方法是创建一个request对象
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
'Connection': 'keep-alive'
}
request = urllib.request.Request(url="http://www.xxxx.com",headers=headers)
response = urllib.request.urlopen(request) 因为我们用Python访问网站的时候一般不会空header,所以都先创建一个request对象,返回的response对象,我们可以看到一些信息
response.info() # 返回的header response.getheaders() # 还是header 只是格式不一样response.getheader("Server") # header中的一个值response.status # 状态码 比如 200 404 500 等response.getcode() # 状态码 函数版response.read() # 返回所有HTMLPOST请求我们在创建request对象的时候加个data就可以了
dict = {
'name':'MIka',
'old:':18
}
data = urllib.parse.urlencode(dict).encode('utf-8') # 要转码,这里就用到 parse
request = urllib.request.Request(url = url,data = data,headers = headers)
response = urllib.request.urlopen(request)Cookie可以用header创建一个,但我常用的的是cookiejar,保存一个cookie,这个我们下次讲