aiohttp小案例

aiohttp简单案例

# -*- coding: utf-8 -*-
"""
    @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())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值