import requests
web = requests.get('https://httpbin.org/anything/get?user=andy')
# web = requests.post('https://httpbin.org/anything/get?user=andy',data={'password':'hello'})
來看看我們發了什麼 request 出去
web.request.__dict__
{'method': 'GET', 'url': 'https://httpbin.org/anything/get?user=andy', 'headers': {'User-Agent': 'python-requests/2.31.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, '_cookies': <RequestsCookieJar[]>, 'body': None, 'hooks': {'response': []}, '_body_position': None}
我們收到了什麼 response 回來?
web.__dict__
{'_content': b'{\n "args": {\n "user": "andy"\n }, \n "data": "", \n "files": {}, \n "form": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.31.0", \n "X-Amzn-Trace-Id": "Root=1-651fbf3e-28c83809666b777a0471e1c7"\n }, \n "json": null, \n "method": "GET", \n "origin": "34.125.116.152", \n "url": "https://httpbin.org/anything/get?user=andy"\n}\n', '_content_consumed': True, '_next': None, 'status_code': 200, 'headers': {'Date': 'Fri, 06 Oct 2023 08:03:10 GMT', 'Content-Type': 'application/json', 'Content-Length': '432', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}, 'raw': <urllib3.response.HTTPResponse at 0x79a2b9e65c30>, 'url': 'https://httpbin.org/anything/get?user=andy', 'encoding': 'utf-8', 'history': [], 'reason': 'OK', 'cookies': <RequestsCookieJar[]>, 'elapsed': datetime.timedelta(microseconds=325027), 'request': <PreparedRequest [GET]>, 'connection': <requests.adapters.HTTPAdapter at 0x79a2b9e67be0>}
web.json()
{'args': {'user': 'andy'}, 'data': '', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.31.0', 'X-Amzn-Trace-Id': 'Root=1-651fbf3e-28c83809666b777a0471e1c7'}, 'json': None, 'method': 'GET', 'origin': '34.125.116.152', 'url': 'https://httpbin.org/anything/get?user=andy'}
input: 網址
output: 把 args 印出來
from urllib.parse import urlparse
url = input()
o = urlparse(url)
o.query
http://127.0.0.1/hello/?user=andy
'user=andy'
如果我想要根據不同路徑,來決定要回傳什麼呢?
url = input()
o = urlparse(url)
if o.path == '/hello':
print(o.query)
elif o.path == '/world':
print('world')
else:
print('index')
http://127.0.0.1/world?user=andy world