napolionic 2021-08-16 09:06 采纳率: 66.7%
浏览 321
已结题

使用python requests session模拟登录后无法取得网页的问题

模拟登陆后尝试访问个人主页,然而会跳转到登陆界面





import requests
from lxml import etree
import json

url_1 = 'http://www.daweilai211.com/Account/Login'

headers = {
    'Referer': 'http://www.daweilai211.com/account/Login',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67'
}


# 获取验证码到本地
html = requests.get(url_1,headers=headers).text
tree_login = etree.HTML(html)
# 获取验证码地址
img_test = tree_login.xpath('/html/body/div[3]/div/div/div/div/form/table/tbody/tr[5]/td[3]/div/img/@src')[0]
img_link = 'http://www.daweilai211.com' + img_test
# 下载该验证码
img = requests.get(img_link,headers=headers).content
with open('./验证码.gif','wb') as fp:
    fp.write(img)
    print('验证码已下载完毕')


code = int(input('请输入得到的验证码:') )
# 找到post的url和之前相同
# 先创建一个session对象来收集cookie

# 输入post的数据
data = {
    'username': 'YN170146',
'password': '276524',
'CheckCode': code
}

session = requests.Session()
url_login = session.post(url_1,headers=headers,data=data)




# 主页:
url_info_scores = 'http://www.daweilai211.com/fangan20/index'
info = session.get(url_info_scores)

info_text = info.text

with open('test.html','w',encoding='utf-8') as fp:
    fp.write(info_text)




  • 写回答

1条回答 默认 最新

  • m0_58995603 2021-08-16 10:23
    关注
    
    import requests
    
    url_1 = 'http://www.daweilai211.com/Account/Login'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 Edg/92.0.902.67',
        'Cookie': 'checkcode=3129'
    }
    data = {
        'username': 'YN170146',
        'password': '276524',
        'CheckCode': '3129'
    }
    session = requests.Session()
    url_login = session.post(url_1, headers=headers, data=data)
    
    # 主页:
    url_info_scores = 'http://www.daweilai211.com/fangan20/index'
    info = session.get(url_info_scores)
    info_text = info.text
    with open('test.html', 'w', encoding='utf-8') as fp:
        fp.write(info_text)
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月25日
  • 已采纳回答 8月17日
  • 创建了问题 8月16日

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示