python爬虫用户名密码登录POST

# -*- coding: utf-8 -*-
"""
Created on Wed Jun  6 13:18:58 2018
 
@author: Lenovo
"""
 
# -*- coding: utf-8 -*-
 
import requests
import urllib
import random
from datetime import datetime
# python2 和 python3的兼容代码
try:
    # python2 中
    import cookielib
    print(f"user cookielib in python2.")
except:
    # python3 中
    import http.cookiejar as cookielib
    print(f"user cookielib in python3.")
 
# session代表某一次连接
huihuSession = requests.session()
# 因为原始的session.cookies 没有save()方法,所以需要用到cookielib中的方法LWPCookieJar,这个类实例化的cookie对象,就可以直接调用save方法。
huihuSession.cookies = cookielib.LWPCookieJar(filename = "huihuCookies.txt")
 
userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
header = {
    # "origin": "https://passport.huihu.cn",
    "Referer": "http://hh.haiper.com.cn/w/wander/user/login/",
    'User-Agent': userAgent,
}
 
def huihuLogin(account, password):
    #
    print ("开始模拟登录嘻嘻嘻")
 
    postUrl = "http://hh.haiper.com.cn/w/wander/user/login/"
    postData = {
        "username": account,
        "password": password,
    }
     
    # 使用session直接post请求
    responseRes = huihuSession.post(postUrl, data = postData, headers = header)
    # 无论是否登录成功,状态码一般都是 statusCode = 200   
    #responseRes = requests.post(postUrl, data = postData, headers = header)
    # 无论是否登录成功,状态码一般都是 statusCode = 200
    print(f"statusCode = {responseRes.status_code}")
    #print(f"text = {responseRes.text}")
    huihuSession.cookies.save()
def isLoginStatus():
    # 通过访问个人中心页面的返回状态码来判断是否为登录状态
    for i in range(2131,2134):
        routeUrl = "http://hh.haiper.com.cn/w/bench/extend/health/trade/all?nickname=&type=&gender=&level=&range%5Bstart%5D=2014-11-11+14%3A57&range%5Bend%5D=2018-06-06+14%3A57&page="+str(i)
         
    # 下面有两个关键点
        # 第一个是header,如果不设置,会返回500的错误
        # 第二个是allow_redirects,如果不设置,session访问时,服务器返回302,
        # 然后session会自动重定向到登录页面,获取到登录页面之后,变成200的状态码
        # allow_redirects = False  就是不允许重定向
        try:
            responseRes = huihuSession.get(routeUrl, headers = header, allow_redirects = False)
            result = responseRes.text
        except:
            continue
        start = result.find('<div class="form-control-static form-control-static-list">')
        result = result[start:]
        #print (result)
        for j in range(1,16):
            start = result.find('擦擦擦图片')
            if start==-1:
                break
            else:
                result = result[start:]
                start = result.find('src="')
                result = result[start+5:]
                end = result.find('" class="img-rounded"')
                imgpath = result[:end]
                print (imgpath)
                if imgpath=='/attachment/':
                    continue
                randomname = datetime.now().strftime("%Y%m%d_%H%M%S") + str(random.randint(1,100))+'.jpg'
                try:
                    urllib.request.urlretrieve(imgpath,'./擦擦擦/'+randomname)
                except:
                    continue
        print (i)
    print(f"isLoginStatus = {responseRes.status_code}")
        #print(f"text = {responseRes.text}")
    if responseRes.status_code != 200:
        return False
    else:
        return True
if __name__ == "__main__":
    # 从返回结果来看,有登录成功
    huihuLogin("xxxx", "xxxx")
    isLogin1 = isLoginStatus()
    print(f"is login huihu = {isLogin1}")

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫可以模拟用户登录,以获取需要登录后才能访问的页面信息。模拟登录的步骤可以总结为以下几个步骤: 1. 找到登录请求:首先,需要到登录页面的请求链接,可以通过查看网页源代码或使用开发者工具来获取该信息。 2. 分析表单:在登录页面中,通常会有一个表单用于输入用户名密码。需要分析该表单的结构,包括表单的URL、请求方式(POST或GET)、表单字段的名称等。 3. 提取加密信息:有些网站会对登录信息进行加密,例如使用RSA或MD5等算法。如果加密信息可被破解,可以提取加密信息并进行解密。如果无法破解,可能需要放弃模拟登录。 4. 构造表单访问:使用Python的网络请求库(如requests)发送一个带有正确登录信息的表单请求。在请求中,需要将用户名密码以及其他必要的登录信息作为表单数据发送给服务器。 通过以上步骤,可以实现Python爬虫模拟用户登录。具体实现的代码和方法可以参考相关的教程和文档,如参考链接所示的CSDN博客文章[2]。请注意,在进行爬虫时,应遵守相关网站的服务条款和法律法规,确保合法合规地进行数据获取。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [python爬虫——模拟登陆](https://blog.csdn.net/qq_16121469/article/details/127718925)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [python爬虫基础(7:模拟登录)](https://blog.csdn.net/Jeeson_Z/article/details/81457337)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值