http запросы в python
В python обычно используют несколько способов:
urllib.request
urllib простой запрос
Официальная одкументация urllib.request
Типичный запрос выглядит так:
from urllib.request import urlopen
with urlopen("https://www.example.com") as response:
body = response.read().decode('utf-8')
body[:15]
# b'<!doctype html>'
upllib post запрос
from urllib import request, parse
data = parse.urlencode(<your data dict>).encode()
req = request.Request(<your url>, data=data) # this will make the method "POST"
resp = request.urlopen(req)
- urllib.request
- requests
- aiohttp
from urllib.request import urlopen
with urlopen("https://www.example.com") as response:
body = response.read().decode('utf-8')
body[:15]
# b'<!doctype html>'
>>> import requests
>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[:15], "...")
asyncio.run(main())