• python使用requests模块模拟登陆知乎


    from bs4 import  BeautifulSoup
    import  requests
    import  time
    
    
    def captcha(captcha_data):
        with open("captcha.jpg",'wb') as f:
            f.write(captcha_data)
        text=input("请输入验证码")
    def zhihuLogin():
       #构建一个session对象,可以保存cookie(相当于urllib中用的cookiejar)
       sess= requests.Session()
       #请求报头
       headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}
    
       #首先获取登陆页面,找到需要POST的数据,同时记录当前页的cookie值
       html=sess.get("https://www.zhihu.com/#signin",headers=headers).text
       bs=BeautifulSoup(html,"lxml")
        #获取之前get的页面的_xsrf值
       #_xsrf防止CSRF攻击(跨站请求伪造),通常叫做跨域攻击,是一种利用网站对用户的一种信任机制来做坏事。
       #跨域攻击一般伪装成网站信任的用户请求(利用cookie),盗取用户信息,欺骗web服务器
       #所以网站会通过设置一个隐藏字段存放这个MD5字符串,这个字符串用来校验用户cookie和服务器cookie
       _xsrf=bs.find("input",attrs={"name":"_xsrf"}).get("value")
    
       #验证码的链接获取,观察发现r的值是根据unix时间戳变得
       captcha_url="https://www.zhihu.com/captcha.gif?r=%d&type=login" % (time.time()*1000)
       #发送请求得到图片数据流
       captcha_data=sess.get(captcha_url,headers=headers).content
       text=captcha(captcha_data)
    
       data={
           "_xsrf":_xsrf,
           "email":"邮箱",
           "password":"密码",
           "captcha":text
       }
       resqonse=sess.post("https://www.zhihu.com/login/email",data=data,headers=headers)
       print(resqonse.text)
       #获取个人主页源码
       #myhomepageresqonse=sess.get("主页url",headers=headers)
    if __name__=="__main__":
        zhihuLogin()
    

      

  • 相关阅读:
    C#中Bitmap类实现对图像操作的一些方法
    C# GDI+ 文字操作
    C#中使用GDI+实现复杂打印
    【Python基础】json.dumps()和json.loads()、json.dump()和json.load()的区分
    【Python爬虫】selenium基础用法
    【Python爬虫】PyQuery解析库
    【Python爬虫】BeautifulSoup 解析库
    【Python爬虫】正则表达式与re模块
    【Python爬虫】Requests库的基本使用
    【Python基础】*args,**args的详细用法
  • 原文地址:https://www.cnblogs.com/c-x-a/p/8023049.html
Copyright © 2020-2023  润新知