PythonでWeb通信

requestsを使う場合

import requests

payload = {"key1": "value1", "key2": "value2"}

r = requests.get('http://httpbin.org/get', params=payload, timeout=5)

print(r.status_code)
print(r.text)
print(r.json())

urllibを使う場合

import urllib.request
import json

url = 'http://httpbin.org/get'

with urllib.request.urlopen(url) as f:
r = json.loads(f.read().decode('utf-8'))
print(r)
print(type(r))

payload = {"key1": "value1", "key2": "value2"}
url = 'http://httpbin.org/get' + '?' + urllib.parse.urlencode(payload)
print(url)

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny

タイトルとURLをコピーしました