使用cookie模拟登录

有些网站需登录才能访问特定页面,抓取此类页面内容时,登录前后情况不同。可使用HTTP包中cookiejar模块支持Cookie,介绍了将Cookie保存到变量、文件,从文件获取Cookie访问,以及利用cookies模拟登录网站等操作。

参考:https://blog.youkuaiyun.com/c406495762/article/details/69817490

1、有些网站需要登录后才能访问某个页面,在登录之前,你想抓取某个页面内容,登陆前与登陆后是不同的,或者不允许的。
  使用Cookie和使用代理IP一样,也需要创建一个自己的opener。在HTTP包中,提供了cookiejar模块,用于提供对Cookie的支持。

2 将Cookie保存到变量中

def getCookeis():
    #declare a cookiejar object instance to save cookie
    cookie=cookiejar.CookieJar();
    #create cookie processor by HTTPCookieProcessor object of urllib.request lib
    handler=request.HTTPCookieProcessor(cookie);
    #create opener
    opener=request.build_opener(handler);
    #open web page
    response=opener.open('http://www.baidu.com')
    for item in cookie:
        print('Name=%s' %item.name)
        print('Value=%s' %item.value)

3、保存Cookie到文件

def getCookiesToTxt():
    filename = '..\\file\cookie.txt'
    cookie = cookiejar.MozillaCookieJar(filename)
    handler=request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(handler)
    response = opener.open('http://www.baidu.com')
    #ignore_discard:even if the cookie will be discared, it will be preserved
    #ignore_expires:if cookies exits in the file,overwrite the original file
    cookie.save(ignore_discard=True, ignore_expires=True)

4、从文件中获取Cookie并访问

def getCookiesFromTxt():
    filename = '..\\file\cookie.txt'
    #create MozillaCookieJar instance object
    cookie = cookiejar.MozillaCookieJar()
    #get cookie from the file to variables
    cookie.load(filename, ignore_discard=True, ignore_expires=True)
    handler=request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(handler)
    response = opener.open('http://www.baidu.com')
    print(response.read().decode('utf-8'))

5、利用cookies模拟登录,这里选择的是http://www.biqukan.comhttps网站总是不成功,这个网站目前是http的

def simulateLogin():
    #login url
    login_url = 'http://www.biqukan.com/user/login.php?action=login&usecookie=1&url=http://www.biqukan.com/'
    #User-Agent infromation
    user_agent = r'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
    #Headers information
    head = {'User-Agnet': user_agent, 'Connection': 'keep-alive'}
    #login Form_Data information
    Login_Data = {}
    Login_Data['password'] = 'yourpassword'
    Login_Data['username'] = 'yourname'

    #convert to standard format
    logingpostdata = parse.urlencode(Login_Data).encode('utf-8')
    cookie = cookiejar.CookieJar()
    cookie_support = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(cookie_support)
    req1 = request.Request(url=login_url, data=logingpostdata, headers=head)

    data_url = 'http://www.biqukan.com/user/bookcase.php'
    req2 = request.Request(url=data_url, headers=head)
    try:
        response1 = opener.open(req1)
        response2 = opener.open(req2)
        html = response2.read().decode('gbk')
        print (html)

    except error.URLError as e:
        if hasattr(e, 'code'):
            print("HTTPError:%d" % e.code)
        elif hasattr(e, 'reason'):
            print("URLError:%s" % e.reason)

 

### 使用 Cookie 模拟网站自动登录的技术实现 #### 背景介绍 Cookie 是一种存储在客户端的小型数据片段,通常用于保存用户的会话状态或其他信息。当用户访问某个网站时,服务器可以通过设置响应头中的 `Set-Cookie` 字段来向浏览器发送 Cookie 数据[^1]。这些 Cookie 可以被后续请求携带到服务器端,从而识别特定的用户身份。 对于自动化脚本来说,可以利用编程语言(如 Python)捕获并管理 Cookies 来模拟登录行为。这种方式的核心在于获取有效的 Session ID 或其他认证令牌,并将其作为 Cookie 发送到目标站点上[^2]。 #### 技术细节与方法 以下是基于 Python 的技术实现方式: 1. **建立 HTTP 请求处理器** 需要创建一个支持处理 cookies 的 opener 对象,在每次发起网络请求的时候都能自动附加已有的 cookie 值。 ```python import http.cookiejar, urllib.request # 初始化 CookieJar 存储器实例 cj = http.cookiejar.CookieJar() # 构建带有 Cookie 处理能力的 Opener opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) ``` 2. **执行初次 POST 登录动作** 向目标服务提交用户名密码等必要参数完成验证过程。如果成功,则返回的结果里应该包含新生成的一组 session-related 的 cookies。 ```python login_url = 'https://example.com/login' post_data = { 'username': 'your_username', 'password': 'your_password' } headers = {'User-Agent': 'Mozilla/5.0'} data_encoded = urllib.parse.urlencode(post_data).encode('utf-8') req = urllib.request.Request(login_url, data=data_encoded, headers=headers) resp = opener.open(req) # 执行登录操作 ``` 3. **保持会话连接进行进一步交互** 成功登录之后,任何由该 opener 创建的新请求都会附带之前收到的所有 cookies ,因此无需再次提供账号凭证就能继续浏览受保护的内容页面。 ```python protected_page_url = 'https://example.com/dashboard' request = urllib.request.Request(protected_page_url, headers=headers) response = opener.open(request) content = response.read().decode('utf-8') # 获取页面内容 print(content[:50]) # 输出前五十字符查看效果 ``` 以上代码展示了如何通过 python 结合标准库模块构建起一套完整的 web 自动化工具链路。 #### 安全注意事项 尽管上述流程能够有效简化某些场景下的开发工作量,但在实际应用过程中仍需注意以下几点安全事项: - 敏感信息加密传输:确保所有的通信都经过 SSL/TLS 加密通道; - 正确销毁过期或不再使用的 sessions 和 tokens; - 不随意暴露真实环境中的账户凭据给第三方程序测试使用; ```python import requests session = requests.Session() login_payload = {"email": "test@example.org", "passwd": "securepass"} r = session.post("http://localhost/api/auth/signin", json=login_payload) if r.status_code == 200 and 'token' in r.json(): dashboard_response = session.get("http://localhost/user/profile") profile_info = dashboard_response.text else: raise Exception("Login Failed!") ``` 此段更简洁版本同样实现了相同功能但采用了 Requests 库替代原始 URLlib 接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值