Python模拟登陆

这里用知乎(www.zhihu.com)来测试的python的模拟登陆操作

首先用FIreFox和Fiddler来拦截所有对知乎的请求,包括进入登陆的页面的url(www.zhihu.com/signin)和登陆的url(www.zhihu.com/login/phone_num)

查看页面的源代码,需要传入一个特殊值:__xsrf=1a2823b23e14b52e9f4867cb5d60d3d3

这个特殊属性是在请求访问 登录页面的时候,从服务器端回传回来的,废话不多说,上代码

#coding:utf-8
import urllib2
import cookielib
import urllib
import re
import sys
from BeautifulSoup import BeautifulSoup

#使用前先安装用python工具pip安装模块
# BeautifulSoup 在线帮助文档
# http://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/


#解决中文报错问题
reload(sys)
sys.setdefaultencoding("utf8")

#####################################
openUrl = 'http://www.zhihu.com/#signin'
loginUrl = 'http://www.zhihu.com/login/phone_num'


# 将cookies绑定到一个opener,cookie由cookielib自动管理
cookie = cookielib.CookieJar()
handler = urllib2.HTTPCookieProcessor(cookie)
opener = urllib2.build_opener(handler)

#设置请求头信息
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Connection': 'keep-alive'
}

#请求参数
data = {
'account': 'phone',
'password': 'pwd',
'remember_me': 'true'
}

try:
# 构造request请求
request = urllib2.Request(openUrl,headers=headers)

# 接收返回的数据
response = urllib2.urlopen(request)
loginPage = response.read()

#读取页面的name: _xsrf -- value: b3bec39ebc84685244ff7288d000cb2c
soup = BeautifulSoup(loginPage)
input = soup.input
#print 'name:',input['name'],' -- value:',input['value']
data[input['name']] = input['value']

# 构造request请求,对参数编码
encodedata = urllib.urlencode(data)
print encodedata
request = urllib2.Request(loginUrl, encodedata, headers=headers)
# 接收返回的数据
response = urllib2.urlopen(request)
loginPage = response.read()

print loginPage
except Exception, e:
print e

原文地址:https://www.cnblogs.com/lianliang/p/5235901.html