'''
Created on 2014-2-20 @author: Vincent
'''
import urllib.parse
import gzip
import json
import re
from http.client import HTTPConnection
from htmlutils import TieBaParser
import httputils as utils # 请求头
headers = dict()
headers["Connection"] = "keep-alive"
headers["Cache-Control"] = "max-age=0"
headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Encoding"] = "gzip,deflate,sdch"
headers["Accept-Language"] = "zh-CN,zh;q=0.8"
headers["Cookie"] = "" # cookie
cookies = list() # 个人信息
userInfo = {} def login(account, password):
'''登录'''
global cookies
headers["Host"] = "wappass.baidu.com"
body = "username={0}&password={1}&submit=%E7%99%BB%E5%BD%95&quick_user=0&isphone=0&sp_login=waprate&uname_login=&loginmerge=1&vcodestr=&u=http%253A%252F%252Fwap.baidu.com%253Fuid%253D1392873796936_247&skin=default_v2&tpl=&ssid=&from=&uid=1392873796936_247&pu=&tn=&bdcm=3f7d51b436d12f2e83389b504fc2d56285356820&type=&bd_page_type="
body = body.format(account, password)
conn = HTTPConnection("wappass.baidu.com", 80)
conn.request("POST", "/passport/login", body, headers)
resp = conn.getresponse()
cookies += utils.getCookiesFromHeaders(resp.getheaders())
utils.saveCookies(headers, cookies)
# 登录成功会返回302
return True if resp.code == 302 else False def getTieBaList():
'''获取已关注的贴吧列表'''
conn = HTTPConnection("tieba.baidu.com", 80)
conn.request("GET", "/mo/m?tn=bdFBW&tab=favorite", "", headers)
resp = conn.getresponse()
tieBaParser = TieBaParser()
tieBaParser.feed(resp.read().decode())
tbList = tieBaParser.getTieBaList()
return tbList def getSignInfo(tieBaName):
'''获取贴吧签到信息'''
queryStr = urllib.parse.urlencode({"kw":tieBaName, "ie":"utf-8", "t":0.571444})
conn = HTTPConnection("tieba.baidu.com", 80)
conn.request("GET", "/sign/loadmonth?" + queryStr, "", headers)
data = gzip.decompress(conn.getresponse().read()).decode("GBK")
signInfo = json.loads(data)
return signInfo tbsPattern = re.compile('"tbs" value=".{20,35}"') def signIn(tieBaName):
'''签到'''
# 获取页面中的参数tbs
conn1 = HTTPConnection("tieba.baidu.com", 80)
queryStr1 = urllib.parse.urlencode({"kw": tieBaName})
conn1.request("GET", "/mo/m?" + queryStr1, "", headers)
html = conn1.getresponse().read().decode()
tbs = tbsPattern.search(html).group(0)[13:-1]
# 签到
conn2 = HTTPConnection("tieba.baidu.com", 80)
body = urllib.parse.urlencode({"kw":tieBaName, "tbs":tbs, "ie":"utf-8"})
conn2.request("POST", "/sign/add" , body , headers)
resp2 = conn2.getresponse()
data = json.loads((gzip.decompress(resp2.read())).decode())
return data def getUserInfo():
'''获取个人信息'''
headers.pop("Host")
conn = HTTPConnection("tieba.baidu.com", 80)
conn.request("GET", "/f/user/json_userinfo", "", headers)
resp = conn.getresponse()
data = gzip.decompress(resp.read()).decode("GBK")
global userInfo
userInfo = json.loads(data) if __name__ == "__main__":
account = input("请输入帐号:")
password = input("请输入密码:") ok = login(account, password)
if ok:
getUserInfo()
print(userInfo["data"]["user_name_weak"] + "~~~登录成功", end="\n------\n")
for tb in getTieBaList():
print(tb + "吧:")
signInfo = signIn(tb)
if signInfo["no"] != 0:
print("签到失败!")
print(signInfo["error"])
else:
print("签到成功!")
print("签到天数:" + str(signInfo["data"]["uinfo"]["cout_total_sing_num"]))
print("连续签到天数:" + str(signInfo["data"]["uinfo"]["cont_sign_num"]))
print("------")
else:
print("登录失败")

baiduclient.py

'''
Created on 2014-2-20 @author: Vincent
''' from html.parser import HTMLParser class TieBaParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.tieBaList = list()
self.flag = False def getTieBaList(self):
return self.tieBaList def handle_starttag(self, tag, attrs):
if tag == "a":
for name , value in attrs:
if name == "href" and "m?kw=" in value:
self.flag = True def handle_data(self, data):
if self.flag:
self.tieBaList.append(data)
self.flag = False

htmlutils.py

'''
Created on 2014-2-20 @author: Vincent
'''
def getCookiesFromHeaders(headers):
'''从http响应中获取所有cookie'''
cookies = list()
for header in headers:
if "Set-Cookie" in header:
cookie = header[1].split(";")[0]
cookies.append(cookie)
return cookies def saveCookies(headers, cookies):
'''保存cookies'''
for cookie in cookies:
headers["Cookie"] += cookie + ";" def getCookieValue(cookies, cookieName):
'''从cookies中获取指定cookie的值'''
for cookie in cookies:
if cookieName in cookie:
index = cookie.index("=") + 1
value = cookie[index:]
return value def parseQueryString(queryString):
'''解析查询串'''
result = dict()
strs = queryString.split("&")
for s in strs:
name = s.split("=")[0]
value = s.split("=")[1]
result[name] = value
return result

httputils.py

转载——Python模拟登录代码的更多相关文章

  1. Python模拟登录代码

    注:访问http://127.0.0.1:8080/user/6,总是会要求必须有登录权限,也就是,若未登录,访问该页面,会跳转到登陆页面. 全自动模拟登录 半自动模拟登录:

  2. 【Python数据分析】Python模拟登录(一) requests.Session应用

    最近由于某些原因,需要用到Python模拟登录网站,但是以前对这块并不了解,而且目标网站的登录方法较为复杂, 所以一下卡在这里了,于是我决定从简单的模拟开始,逐渐深入地研究下这块. 注:本文仅为交流学 ...

  3. [Python] Python 模拟登录,并请求

    Python 模拟登录,并请求 # encoding: utf- import requests import socket import time socket.setdefaulttimeout( ...

  4. 【py登陆】python模拟登录

    用Python模拟登录网站 前面简单提到了 Python 模拟登录的程序,但是没写清楚,这里再补上一个带注释的 Python 模拟登录的示例程序.简单说一下流程:先用cookielib获取cookie ...

  5. 忘记秘密利用python模拟登录暴力破解秘密

    忘记秘密利用python模拟登录暴力破解秘密: #encoding=utf-8 import itertools import string import requests def gen_pwd_f ...

  6. Python模拟登录实战(三)

    目标:模拟登录知乎 代码如下: #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'ziv·chan' import re impor ...

  7. Python模拟登录实战(二)

    目标:1.模拟登录豆瓣,2.自动更改签名和发表说说. 代码如下: #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'ziv·chan ...

  8. Python模拟登录实战(一)

    今天,学习了模拟登录新浪微博.模拟登录主要有两种方式,一.利用Cookie:二.模仿浏览器的请求,发送表单. 法一: Cookie:指某些网站为了辨别用户身份而储存在用户本地终端上的数据(通常经过加密 ...

  9. Python模拟登录的几种方法

    目录 方法一:直接使用已知的cookie访问 方法二:模拟登录后再携带得到的cookie访问 方法三:模拟登录后用session保持登录状态 方法四:使用无头浏览器访问 正文 方法一:直接使用已知的c ...

随机推荐

  1. BZOJ 3782 上学路线

    首先这个题需要dp.dp[i]=C(x[i]+y[i],x[i])-Σdp[j]*C(x[i]-x[j]+y[i]-y[j],x[i]-x[j])(x[i]>=x[j],y[i]>=y[j ...

  2. WCF之多个协定

    多个协定”示例演示如何在一个服务上实现多个协定,以及如何配置终结点以便与实现的每个协定进行通信 1.服务端代码如下(服务实现了两个协定,增加了黄色所示代码): class Program { stat ...

  3. Web页面性能测试工具浅析

    http://www.cnblogs.com/fo0ol/p/3297054.html 做Web开发,难免要对自己开发的页面进行性能检测,自己写工具检测,工作量太大.网上有几款比较成熟的检测工具,以下 ...

  4. Python 获取 网卡 MAC 地址

    /*********************************************************************** * Python 获取 网卡 MAC 地址 * 说明: ...

  5. 使用SCP在命令行传输文件

    下载远程服务器上的文件 scp   root@10.0.10.10:/home/user/download.txt  ./download.txt 上传文件到远程服务器 scp  ./upload.t ...

  6. hive数据导入方法

    可以通过多种方式将数据导入hive表 1.通过外部表导入 用户在hive上建external表,建表的同时指定hdfs路径,在数据拷贝到指定hdfs路径的同时,也同时完成数据插入external表. ...

  7. html5实现饼图和线图-我们到底能走多远系列(34)

    我们到底能走多远系列(34) 扯淡: 送给各位一段话:     人生是一个不断做加法的过程     从赤条条无牵无挂的来     到学会荣辱羞耻 礼仪规范     再到赚取世间的名声 财富 地位    ...

  8. sql server导入mdf 报操作系统错误 5:“5(拒绝访问。)”

    错误一:拒绝访问 在安装示例库时出现以下的错误 消息 5120,级别 16,状态 101,第 1 行无法打开物理文件"D:\Download\AdventureWorks2012_Data. ...

  9. android的style控制Theme

    value-v14就是在API14(4.0)的手机上所使用的Theme(其他版本以此类推) theme的名字叫做AppTheme,后面写有继承自哪个Theme,如下所示 <style name= ...

  10. Java-->List&Set

    一.List集合 特点:有序可重复 List集合的猜想: 1.每个元素是不是应该有序号 index 2.addFirst.addLast.set(intdex, 对象) 3.get(index)... ...