aiohttp简单案例
"""
@Author: kong
@File : login.py
@Date : 2023-04-09 21:17:04
@notes : Aiohttp 请求
"""
from ast import literal_eval
import re
import asyncio
import aiohttp
FLAG: bool = True
try:
import aiofiles
from bs4 import BeautifulSoup
except ImportError:
FLAG = False
async def fetch(url):
""" 请求函数 """
async with aiohttp.ClientSession(headers=header) as session:
async with session.get(url) as resp:
html = await resp.text()
if FLAG:
await save_file(html, "login.html")
return html
async def save_file(content, filename):
""" 存储函数 """
async with aiofiles.open(file=filename, mode="w", encoding="utf-8") as f:
await f.write(content)
print("File is Saved!")
async def login_net():
""" 登陆 """
params = [
('callback', 'dr1003'),
('DDDDD', username),
('upass', password),
('0MKKey', '123456'),
('R1', '0'),
('R2', ''),
('R3', '0'),
('R6', '0'),
('para', '00'),
('v6ip', ''),
('terminal_type', '1'),
('lang', 'zh-cn'),
('jsVersion', '4.2'),
('v', '9272'),
('lang', 'zh'),
]
login_url = 'http://10.253.0.1/drcom/login'
async with aiohttp.ClientSession(headers=header) as session:
async with session.get(login_url, params=params) as resp:
html = await resp.text()
return html
async def parser_html(login_url: str, html: str):
""" 解析函数 """
soup = BeautifulSoup(html, 'lxml')
title: str = soup.title.string
if title == "上网登录页":
print(f"Will login to network server => {login_url}")
login_resp: str = await login_net()
login_info: dict = literal_eval(
re.findall(r"dr1003\((.*?)\)", login_resp)[0]
)
return login_info
elif title == "注销页":
return "Login seffully!"
async def main():
""" 主程序 """
fetch_url: str = "http://10.253.0.1"
html = await fetch(fetch_url)
if not FLAG:
await login_net()
info = await parser_html(fetch_url, html)
print(info)
if __name__ == "__main__":
header = {
'Accept':
'*/*',
'Accept-Language':
'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'Connection':
'keep-alive',
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.62',
}
username: str = ...
password: str = ...
asyncio.run(main())