1. 程式人生 > >Python:Urllib庫使用

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'