Python:Urllib库使用

import urllib

response = urllib.request.urlopen("https://www.python.org")

#返回响应的状态码
print(response.status)
#返回响应的头信息
print(response.getheaders())
#获取响应头中Server的值
print(response.getheader("Server"))

# 运行结果如下:
# 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 13:57:18 GMT'), ('Via', '1.1 varnish'), ('Age', '306'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2141-IAD, cache-sjc3139-SJC'), ('X-Cache', 'HIT, HIT'), ('X-Cache-Hits', '3, 17'), ('X-Timer', 'S1542808639.835715,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
# nginx
import urllib.parse
import urllib.request


#将参数转化为bytes类型,第二个参数指定编码格式为utf-8
data = bytes(urllib.parse.urlencode({"word": "hello"}), encoding="utf-8")
print(data)
response = urllib.request.urlopen("http://httpbin.org/post", data=data)
print(response.read())

# 运行结果如下
# b'word=hello'
# b'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "word": "hello"\n  }, \n  "headers": {\n    "Accept-Encoding": "identity", \n    "Connection": "close", \n    "Content-Length": "10", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "httpbin.org", \n    "User-Agent": "Python-urllib/3.6"\n  }, \n  "json": null, \n  "origin": "111.47.249.5", \n  "url": "http://httpbin.org/post"\n}\n'

猜你喜欢

转载自www.cnblogs.com/mq-b/p/9998168.html