urllib使用
urllib是python内置的HTTP库,urllib主要分为以下4个功能模块:
- request(请求)
- parse(解析)
- error(异常处理)
- robotparser(识别robots.txt文件)
请求
使用urllib.request模块的urlopen()获取页面
urllib.request.urlopen(url, data=None, [timeout,]*, cafile=None, capath=None, cadefault=False, context=None)
url: 需要打开的网址
data: post提交的数据
timeout: 设置网站的访问超时时间
Get请求
def req_op(): response = request.urlopen('http://www.baidu.com') print(response.read().decode('utf-8')) # 返回的数据格式为bytes类型,需要decode()解码,转换成str类型 print(response.info()) # 返回HTTPMessage对象,表示远程服务器 返回的头信息 print(response.getcode()) # 返回Http状态码 print(response.geturl()) # 返回请求的url print(response.status) # 返回状态码 print(response.getheaders()) # 响应的头部信息 print(response.getheader('Server')) # 返回响应头指定参数Server 的值 if __name__ == '__main__': req_op()
Post请求
data = {'word':'hello'}
data = urllib.parse.urlencode(data).encode('utf-8')
# data = bytes(urllib.parse.urlencode(data),encoding='utf-8') # 第二种方式
response = urllib.request.urlopen('http://locahost:8080/post',data=data) # data以bytes形式传入;为可选参数,加上即为post请求
print(response.read())
使用urllib.request模块的Request包装请求,再通过urlopen()获取页面
urllib.request.Request(url, data=None,
headers={},method=None)
Get请求
def req_op(): req = request.Request('http://www.baidu.com') response = request.urlopen(req) print(response.read().decode('utf-8')) # 返回的数据格式为bytes类型,需要decode()解码,转换成str类型
Post请求
url = 'http://localhost:8080/post' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64)', 'Host':'huo.org'} data = {'name':'jack'} data = parse.urlencode(data).encode('utf-8') req = request.Request(url=url,headers=headers,data=data,method='POST') response = request.urlopen(req) print(response.read().decode('utf-8'))
异常处理
HTTPError是URLError的子类,他的异常有3个属性
code:返回状态码404表示不存在,500表示服务器错误
reason:返回错误原因
headers:返回请求头
def req_op(): try: req = request.Request('http://www.baidus.com') response = request.urlopen(req) print(response.read().decode('utf-8')) # 返回的数据格式为bytes类型,需要decode()解码,转换成str类型 except error.URLError as e: print(e.code, e.reason) print(e.headers) -------------------结果--------------------- 403 Forbidden date: Fri, 25 Mar 2022 09:28:43 GMT content-type: text/html content-length: 150 vary: Accept-Encoding server: NginX connection: close
添加Cookie
import http.cookiejar, urllib.request cookie = http.cookiejar.CookieJar() # 创建一个cookiejar对象 handler = urllib.request.HTTPCookieProcessor(cookie) # 使用HTTPCookieProcessor创建cookie处理器 opener = urllib.request.build_opener(handler) # 构建Opener对象 # request.install_opener(opener) # 将此opener设置为全局的opener response = opener.open('http://www.baidu.com') for item in cookie: print(item.name+":"+item.value)
立志如山 静心求实
浙公网安备 33010602011771号