Python:Urllib库使用

Python网络请求详解
本文深入讲解了使用Python进行网络请求的方法,包括获取响应状态、响应头信息,POST请求的参数处理,以及超时处理和异常捕获。通过具体示例展示了如何使用urllib库进行HTTP请求,适用于初学者及进阶读者。
import urllib.request

response = urllib.request.urlopen("http://www.python.org")
print(response.status) #获取响应码
print(response.getheaders()) #获取响应头信息
print(response.getheader("Server")) #获取响应头中Server的值
print(response.getheader('Content-Type'))

"""
运行结果如下:
200
[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'SAMEORIGIN'), ('x-xss-protection', '1; mode=block'), ('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Via', '1.1 varnish'), ('Content-Length', '50114'), ('Accept-Ranges', 'bytes'), ('Date', 'Wed, 21 Nov 2018 14:28:32 GMT'), ('Via', '1.1 varnish'), ('Age', '1610'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2141-IAD, cache-lax8624-LAX'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '4, 107'), ('X-Timer', 'S1542810512.220409,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx
text/html; charset=utf-8
"""
import urllib

data = bytes(urllib.parse.urlencode({"word":"hello"}), encoding="utf8")
print(data)  #将参数转换成bytes类型  b'word=hello'
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read().decode("utf-8"))

import urllib.request
import socket
import urllib.error

try:  #timeout实现超时处理
    response = urllib.request.urlopen("http://httpbin.org/get", timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout): #isinstance判断异常对象是不是时间类型
        print("TIME OUT")

import urllib
request = urllib.request.Request("http://python.org")
response = urllib.request.urlopen(request)
print(response.read().decode("utf-8"))

 

转载于:https://www.cnblogs.com/mq-b/p/9998168.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值