使用python请求登录网站(续)

2024-06-17 13:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在S/O上发布了一个问题,我得到的回复帮助我向前迈出了一大步,所以我又来了。(这是在Login to a website using python requests;我应该“回答”这个帖子,为了问这个补充性的问题,还是应该“问”一个全新的问题,像这里一样?)(然后我可以删除这个)

我遇到了一些困难,从一个python脚本登录到一个网站,为了检索数据从它以后,一旦我将连接。 通过以下POST请求,我的代码似乎成功通过了登录的标识阶段:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
password = 'VeryStrong'
sess = requests.Session()
user_agent = {'User-agent': 'Mozilla/5.0'}
pars11 = { 'login': 'dva2tlse', 'pass': password }
url11 = "http://www.example.com/login/loginSubmit"
resp11 = sess.post(url11, data=pars11) # Sends a POST request. Returns Response object

然后我记录了一个包含我收到的响应的文件:

Fichier = open('resp11.html', 'w')
Fichier.write(resp11.content)
Fichier.close()
print '\n\t\tOk, resp11.url='+resp11.url+', resp11.status_code=%i' % (resp11.status_code)
# Ok, resp11.url=http://www.example.com/home, resp11.status_code=200
print '\n\t\tfirefox -P def2 -no-remote resp11.html &\n' # to inspect the first recorded page

这个文件的内容,在任何导航器中都可以看到,显示证明登录成功的个人信息。你知道吗

然后我尝试“用户”页面并检查收到的响应:

url12 = "http://www.example.com/friends"
resp12 = sess.get(url12)
Fichier = open('resp12.html', 'w')
Fichier.write(resp12.content)
Fichier.close()
print '\n\t\tOk, resp12.url='+resp12.url+', resp12.status_code=%i' % (resp12.status_code)
# Ok, resp12.url=http://www.example.com/home, resp12.status_code=200
print '\n\t\tfirefox -P def2 -no-remote resp12.html &\n' # to inspect the second recorded page

第二个页面,一旦登录,应该显示一个“用户”页面,但它只显示相同的“/主页”页面,和以前一样。 我能用它做什么? 大卫


Tags: tocomhttpurlexamplehtmlwwwstatus