Python获取Cookie或鉴权方法封装

通过urllib.request爬取网址信息,re正则表达式获取Cookie或Authorization

import urllib.request
import re


def get_authorization(url, pat):
    """获取Cookie或鉴权"""
    try:
        file = urllib.request.urlopen(url, timeout=1).info()
        string = file["Set-Cookie"]
        res = re.compile(pat).findall(string)
        return res
    except Exception as error:
        print(f"出现异常:{error}")


if __name__ == '__main__':
    url = "https://blog.csdn.net/weixin_42760923"
    pat = "acw_tc=(.*);path"
    print(get_authorization(url, pat))

猜你喜欢

转载自www.cnblogs.com/CesareZhang/p/12110918.html
今日推荐