-
功能
- 批量获取微博博文mid(每篇博文唯一id)并插入数据库
- 批量登录微博账号(无需验证码,为什么我也不知道,一个账号需要.4个账号就直接上去了)并插入数据库
- 批量发表随机微博
- 批量转发微博(开发中)
- 批量关注微博(开发中)
- 批量发私信(开发中)
- 批量发评论(已完成)
- 多线程(已完成80%)
- 代理请求(开发中)
-
目录结构
-
WeiBo
-
Mode
- __init__.py
- Conn.py
- Get_Data.py
- Get_Mid.py
- Login_Session.py
- Post.py
- Send_Content.py
- User_Agent.py
-
data
- account.config
- content.config
- cookie.config
- send_content.config
- user_agent.config
- Main.py
-
Mode
-
WeiBo
-
数据库结构
-
autodrain(数据库)
-
cookies
- id(id)
- cookies(cookies)
-
proxy
- id
- addres(ip地址)
- port(端口)
- anonymous(是否匿名)
- types(代理类型)
- position(位置)
- delay(延迟)
- last_test(最后测试时间)
-
user
- id(单条信息id,主键自增)
- mid(博文id)
- source(发表使用的手机型号)
- text(博文内容)
- comments_count(忘了)
- reposts_count(转发数量)
- avatar_hd(高清头像url)
- description(个人简介)
- mbrank(会员等级)
- urank(账号等级)
- verified_reason(认证说明)
- follow_count(关注人数)
- followers_count(粉丝数量)
- gender(性别m男f女)
- screen_name(昵称)
- statuses_count(发表文章数量)
- profile_url(用户主页url)
-
temp_mid
- id(id)
- mid(博文mid)
-
cookies
-
autodrain(数据库)
# Main.py
# _*_ coding: utf-8 _*_
import sys
import time
import string
import threading
import datetime
import sys
sys.path.append("../../")
from model.WeiBo.Mode import Get_Data,Post,Login_Session,Send_Content
def Main():
Post.Go()
def Send():
Send_Content.Start()
if __name__ == '__main__':
# Cookie()
Main()
# Send()
# mid = "4388669999421483"
# Post.Start(Login_Session.Main(Get_Data.Account()),mid)
# Conn.py
# -*- coding: UTF-8 -*-
import types
import pymysql
import pymysql.cursors
# def Main(mid,source,text,user_id,user_avatar_hd,user_badge_bind_taobao,user_badge_user_name_certificate,user_description,user_mbrank,user_urank,user_profile_url,user_verified_reason,user_follow_count,user_followers_count,user_gender,user_screen_name,user_statuses_count):
# # 打开数据库连接
# db = pymysql.connect("localhost", "root", "root", "autodrain", charset = 'utf8')
# # 使用cursor()方法获取操作游标
# cursor = db.cursor()
# cursor.execute("SELECT VERSION()")
# sql = """INSERT INTO mblog_user ('mid', 'source','source','text','user_id','user_avatar_hd','user_badge_bind_taobao','user_badge_user_name_certificate','user_description','user_mbrank','user_urank','user_profile_url','user_verified_reason','user_follow_count','user_followers_count','user_gender','user_screen_name','user_statuses_count') VALUES('test1', 1),('test2', 2),('test3', 3),('test4', 4),('test5', 5),('test6', 6);"""
# try:
# # 获取一个游标
# with db.cursor() as cursor:
# sql = 'select * from mblog_user'
# cout = cursor.execute(sql)
# print("数量: " + str(cout))
# db.commit()
#
# finally:
# db.close()
def GetConn():
try:
db = pymysql.connect("127.0.0.1", "root", "root", "autodrain", charset = 'utf8')
return db
except:
print("数据库连接失败,请检查")
#查询数据并返回结果集
def Find_All():
# 打开数据库连接
db = GetConn()
# 使用cursor()方法获取操作游标
try:
# 获取一个游标
with db.cursor() as cursor:
sql = 'select * from user'
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
mid = row[3]
print(mid)
db.commit()
return results
finally:
db.close()
# def Inter_Data=""
# def Main(mid,source,text,user_id,user_avatar_hd,user_badge_bind_taobao,user_badge_user_name_certificate,user_description,user_mbrank,user_urank,user_profile_url,user_verified_reason,user_follow_count,user_followers_count,user_gender,user_screen_name,user_statuses_count):
# Post.py
# _*_ coding: utf-8 _*_
import requests
import threading
import random
import time
import re
import sys
sys.path.append("../../../")
from model.WeiBo.Mode import Conn,User_Agent
def Head(cook):
user_agent = User_Agent.Main()
headers = {
"authority": "www.weibo.com",
"method": "POST",
"path": "/aj/v6/comment/add?ajwvr=6&__rnd=" + str(int(round(time.time() * 1000))),
"scheme": "https",
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh,zh-CN;q=0.9",
"content-length": "162",
"content-type": "application/x-www-form-urlencoded",
"cookie": cook,
"origin": "https://www.weibo.com",
"referer": "https://www.weibo.com/u/2527670372?is_hot=1",
"user-agent": user_agent,
"x-requested-with": "XMLHttpRequest"
}
return headers
def Url_Data():
url_str1 = "https://www.weibo.com/aj/v6/comment/add?ajwvr=6&__rnd=" + str(int(round(time.time() * 1000)))
# url_str2= "https://www.weibo.com/aj/v6/comment/add?ajwvr=6&__rnd=1561631552951"
# url_str3= "https://www.weibo.com/aj/v6/comment/add?ajwvr=6&__rnd=1561631552951"
# str = [url_str1,url_str2,url_str3]
return url_str1
def Post_Data(uid, mid, ci):
str1 = "第" + str(ci) + "次,调试2"
data = {
"act": "post",
"mid": mid,
"uid": uid,
"forward": "0",
"isroot": "0",
"content": str1,
"location": "page_103505_home",
"module": "scommlist",
"group_source": "",
"pdetail": "1035052527670372",
"_t": "0",
}
# "pdetail": "1035052527670372",
# print("UID:",uid)
return data
'''
函数内参数
Fail_Pan:判断挂了多少次,次数超过5次自动切断程序运行;int类型
Number_For:每个账号循环多少次/提交多少次;int类型
函数传参参数
cook:包含每个用户的cook和uid,list类型
mid:目标博文mid参数;string类型
调用本函数必须要给的参数
cookies:列表类型
pdetail:string类型
mid:string类型
'''
def Get_Mid():
db = Conn.GetConn()
res = []
try:
# 获取一个游标
with db.cursor() as cursor:
sql = 'select mid from user'
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
mid = row[0]
res.append(mid)
db.commit()
finally:
db.close()
return random.choice(res)
#获取cookies
def Cook():
cookies = []
T = True
while T:
try:
db = Conn.GetConn()
cur = db.cursor()
sql = "select * from cookies"
cur.execute(sql)
res = cur.fetchall()
for row in res:
cookies.append(row[1])
db.commit()
db.close()
T = False
return cookies
except:
print(" ===================获取Cookies错误,正在重新获取===============\n")
def Start(start,stop):
T = True
while T:
try:
cookies = Cook()
num = 1
uid = []
cook = []
Fail_Pan = 1
# Number_For = 20
url = Url_Data()
for c in range(0, int(len(cookies))): # 提取cookies和uid并添加到列表
uid.append(str(re.findall(r"____________(..........+?)", str(cookies[c]))).replace("['", "").replace("']", ""))
cook.append(str(re.findall(r"(.+?)____________", str(cookies[c]))).replace("['", "").replace("']", ""))
for cok in range(0, int(len(cookies))): # 每个账号的循环
# for cok in range(start, stop): # 每个账号的循环
cook_use = cook[cok] # 获取单次cookie
uid_use = uid[cok] # 获取单次uid
for x in range(start,stop): # 循环次数及提交
hander = Head(cook_use) # 获取每次提交的请求头
mid = str(Get_Mid())
post_data = Post_Data(uid_use, mid, num) # 获取每次提交的Post内容
resp = requests.post(url, post_data, headers = hander, timeout = 5) # 提交
if "100000" in resp.text:
print("\n ===================第", str(num), "次刷评论,成功===============\n")
num = num + 1
continue
elif "100001" in resp.text:
print("\n ==============第", str(x + 1), "次失败,原因:次数太多=============\n")
Fail_Pan = Fail_Pan + 1
continue
elif "100002" in resp.text:
print("\n ========================失败,原因:服务暂停多=======================\n")
Fail_Pan = Fail_Pan + 1
continue
elif "100024" in resp.text:
print("\n ============失败,原因:用户请求特殊接口 (%s) 频次超过上限==========\n")
Fail_Pan = Fail_Pan + 1
continue
elif "100012" in resp.text:
print("\n ==========================失败,原因:非法请求多 时间:",'\033[1;32m' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + '\033[0m'"==============\n")
time.sleep(2)
Fail_Pan = Fail_Pan + 1
continue
if Fail_Pan >= 50:
t = random.randint(300, 800)
print("")
print("\n --------所有账号全部受限,", str(int(t/60)), "分钟后自动重起程序-------\n")
print("")
print("")
time.sleep(t)
continue
except:
print("\n ------------------------未知错误,重新启动---------------------\n")
#设置开启多少线程,双层循环,最外层控制循环倍数
def Go():
start = 1
stop = 0
for x in range(0,1):
for t in range(0,30):
stop = stop + 200
thread = threading.Thread(target = Start,args = (start,stop))
thread.start()
print(" ==========================第",str(t+1),"线程开启成功====================\n")
start = start + 200
# def Main():
# Start()
# if __name__ == "__main__":
# Start(50, 0)
#Get_Data.py
# _*_ coding: utf-8 _*_
import random
import re
#提取关键字
def Get_Random_Key():
file = open("data/content.config",'r+',encoding = "utf-8")
file = file.readlines()
data = []
for line in file:
data.append(str(line).replace("\n",""))
# print(data)
# temp = random.choice(data)
return data
#提取账号
def Account():
file = open("Mode/data/account.config",'r')
# file = open("data/account.config",'r')
file = file.readlines()
data = []
for x in file:
data.append(x)
Account = []
Password = []
for account in range(0,int(len(data))):
zhanghao = str(re.findall(r"(.+?):", str(data[account]))).replace("['",'').replace("']",'')
Account.append(zhanghao)
for password in range(0,int(len(data))):
mima = str(re.findall(r":(..........+?)*", str(data[password]))).replace("['",'').replace("']",'')
Password.append(mima)
# List_Data = [Account,Password]
return Account
#提取文章
def Wen_Zhang_Content():
file = open("Mode/data/send_content.config",'r',encoding = "utf-8")
file = file.readlines()
data = []
for line in file:
data.append(str(line).replace("\n",""))
temp = random.choice(data)
return temp
#提取Cookies
def Cookies():
file = open("Mode/data/cookie.config",'r',encoding = "utf-8")
file = file.readlines()
data = []
for line in file:
data.append(str(line).replace("\n",""))
return data
#提取User_Agent
def Get_User_Agent():
file = open("data/user_agent.config",'r',encoding = "utf-8")
file = file.readlines()
data = []
for line in file:
data.append(str(line).replace("\n",""))
data = random.choice(data)
return data
# if __name__ == '__main__':
# Main()
# Content()
# Get_Mid.py
# -*- coding: UTF-8 -*-
import requests
import urllib.parse
import json
import json.decoder
import Get_Data, Conn
import random
import re
import time
import threading
#获取随机伪造请求头
def Hand():
hand = {
"Accept": "application/json, text/plain, */*",
"MWeibo-Pwa": "1",
"Referer": "https://m.weibo.cn/",
"User-Agent": Get_Data.Get_User_Agent(),
"X-Requested-With": "XMLHttpRequest",
}
return hand
# 获取微博用户的基本信息,如:微博昵称、微博地址、微博头像、关注人数、粉丝数、性别、等级等
# def Get_User_Data(url, proxy_addr):
# api = "https://m.weibo.cn/api/container/getIndex?type=uid&value=1556349391"
# data = use_proxy(url, proxy_addr)
# content = json.loads(data).get('data')
# profile_image_url = content.get('userInfo').get('profile_image_url')
# description = content.get('userInfo').get('description')
# profile_url = content.get('userInfo').get('profile_url')
# verified = content.get('userInfo').get('verified')
# guanzhu = content.get('userInfo').get('follow_count')
# name = content.get('userInfo').get('screen_name')
# fensi = content.get('userInfo').get('followers_count')
# gender = content.get('userInfo').get('gender')
# urank = content.get('userInfo').get('urank')
#取随机关键词
def Get_Random_Key():
key = Get_Data.Get_Random_Key()
return random.choice(key)
# 获取dict值
def get_target_value(key, dic, tmp_list):
"""
:param key: 目标key值
:param dic: JSON数据
:param tmp_list: 用于存储获取的数据
:return: list
"""
if not isinstance(dic, dict) or not isinstance(tmp_list, list): # 对传入数据进行格式校验
return 'argv[1] not an dict or argv[-1] not an list '
if key in dic.keys():
tmp_list.append(dic[key]) # 传入数据存在则存入tmp_list
else:
for value in dic.values(): # 传入数据不符合则对其value值进行遍历
if isinstance(value, dict):
get_target_value(key, value, tmp_list) # 传入数据的value值是字典,则直接调用自身
elif isinstance(value, (list, tuple)):
_get_value(key, value, tmp_list) # 传入数据的value值是列表或者元组,则调用_get_value
return tmp_list
def _get_value(key, val, tmp_list):
for val_ in val:
if isinstance(val_, dict):
get_target_value(key, val_, tmp_list) # 传入数据的value值是字典,则调用get_target_value
elif isinstance(val_, (list, tuple)):
_get_value(key, val_, tmp_list) # 传入数据的value值是列表或者元组,则调用自身
#删除重复
def Get_No_Many(list_Get):
data = list(set([val for i in list_Get for val in i]))
return data
def Main(start,stop):
num = 0
mid = []
source = []
text = []
comments_count = []
reposts_count = []
avatar_hd = []
description = []
mbrank = []
urank = []
verified_reason = []
follow_count = []
followers_count = []
gender = []
screen_name = []
statuses_count = []
profile_url = []
try:
for x in range(start,stop):
try:
print(" ============================正在循环第", str(x), "次===================\n")
headers = Hand()
strt = "=1&q=" + str(Get_Random_Key())
url = "https://m.weibo.cn/api/container/getIndex?containerid=100103type" + str(urllib.parse.quote(strt)) + "&page_type=searchall&page=" + str(x)
try:
resp = requests.get(url, headers = headers, timeout = 3)
if resp.content:
js = json.loads(str(str(str(resp.text))))
mid.append(get_target_value("mid", js, []))
source.append(get_target_value("source", js, []))
text.append(get_target_value("text", js, []))
comments_count.append(re.findall(r"comments_count':(.+?),",str(js)))
reposts_count.append(str(get_target_value('reposts_count', js, [])))
avatar_hd.append(get_target_value('avatar_hd', js, []))
description.append(get_target_value('description', js, []))
mbrank.append(str(get_target_value('mbrank', js, [])))
urank.append(str(get_target_value('urank', js, [])))
verified_reason.append(str(get_target_value('verified_reason', js, [])))
follow_count.append(str(get_target_value('follow_count', js, [])))
followers_count.append(str(get_target_value('followers_count', js, [])))
gender.append(get_target_value('gender', js, []))
screen_name.append(get_target_value('screen_name', js, []))
statuses_count.append(str(get_target_value('statuses_count', js, [])))
profile_url.append(get_target_value('profile_url', js, []))
else:
# t = random.randint(5,100)
# time.sleep(t)
# print(" ============================第", str(x), "次无返回,休息",t,"秒===================\n")
continue
except:
print("错误")
continue
# 去重复项,comments_count,reposts_count,mbrank,urank不去重
mid = Get_No_Many(mid)
source = Get_No_Many(source)
text = Get_No_Many(text)
comments_count = Get_No_Many(comments_count)
reposts_count = Get_No_Many(reposts_count)
avatar_hd = Get_No_Many(avatar_hd)
description = Get_No_Many(description)
# mbrank = Get_No_Many(mbrank)
# urank = Get_No_Many(urank)
# screen_name = Get_No_Many(screen_name)
# verified_reason = Get_No_Many(verified_reason)
# follow_count = Get_No_Many(follow_count)
# followers_count = Get_No_Many(followers_count)
# gender = Get_No_Many(gender)
# statuses_count = Get_No_Many(statuses_count)
# profile_url = Get_No_Many(profile_url)
#备份sql语句
# mid[to_db], source[to_db], text[to_db], comments_count[to_db], reposts_count[to_db], scheme[to_db], avatar_hd[to_db], description[to_db], mbrank[to_db], urank[to_db], verified_reason[to_db], follow_count[to_db], followers_count[to_db], gender[to_db], screen_name[to_db], statuses_count[to_db], profile_url[to_db]
for to_db in range(0, int(len(mid))):
if len(mid[to_db]) < 10:
continue
elif not int(len(source)) == int(len(mid)-int(len(source))) or source[to_db] != "":
for sou in range(0,int(len(mid))):
source.extend("N")
# elif not int(len(text)) == int(len(mid)) or text[to_db] != "":
# for tex in range(0,int(len(mid))-int(len(text))):
# text.extend("N")
# elif not int(len(comments_count)) == int(len(mid)) or comments_count[to_db] != "":
# for com in range(0,int(len(mid))-int(len(comments_count))):
# comments_count.extend("N")
# elif not int(len(reposts_count)) == int(len(mid)) or reposts_count[to_db] != "":
# for rep in range(0,int(len(mid))-int(len(reposts_count))):
# reposts_count.extend("N")
# elif not int(len(mbrank)) == int(len(mid)) or mbrank[to_db] != "":
# for rep in range(0,int(len(mid))-int(len(mbrank))):
# mbrank.extend("N")
# elif not int(len(urank)) == int(len(mid)) or urank[to_db] != "":
# for rep in range(0,int(len(mid))-int(len(urank))):
# urank.extend("N")
# elif not int(len(verified_reason)) == int(len(mid)):
# for rep in range(0,int(len(mid))-int(len(verified_reason))):
# verified_reason.extend("N")
# elif not int(len(follow_count)) == int(len(mid)):
# for fol in range(0,int(len(mid))-int(len(follow_count))):
# follow_count.extend("N")
# elif not int(len(profile_url)) == int(len(mid)):
# for fol in range(0,int(len(mid))-int(len(profile_url))):
# profile_url.extend("N")
db = Conn.GetConn()
num = num + 1
# sql_insert = """insert into user(mid, source, text, comments_count, reposts_count, scheme, avatar_hd, description, mbrank, urank, verified_reason, follow_count, followers_count, gender, screen_name, statuses_count, profile_url) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')""" % (mid[to_db], source[to_db], text[to_db], comments_count[to_db], reposts_count[to_db],scheme[to_db], avatar_hd[to_db], description[to_db], mbrank[to_db], urank[to_db], verified_reason[to_db],follow_count[to_db], followers_count[to_db], gender[to_db], screen_name[to_db], statuses_count[to_db],profile_url[to_db])
sql_insert = """insert into user(mid,source,text,comments_count,reposts_count,avatar_hd,description) values('%s','%s','%s','%s','%s','%s','%s')""" % (mid[to_db],source[to_db],text[to_db],comments_count[to_db],reposts_count[to_db],avatar_hd[to_db],description[to_db])
sql_find = "select mid from user where mid=('%s')" % (mid[to_db])
try:
cursor = db.cursor()
try:
cursor.execute(sql_find)
results = cursor.fetchall()
if not results:
try:
cursor.execute(sql_insert)
db.commit() # 提交到数据库执行
print(" ============================第", str(num),"条 插入数据库成功===================\n")
except:
print(" ============================第", str(num),"条 其他未知错误 ===================\n")
continue
else:
print(" ============================第", str(num),"条 插入数据重复 ===================\n")
continue
except:
print(" ============================第", str(num),"条 其他未知错误 ===================\n")
continue
except:
print(" ============================第", str(num),"条 其他未知错误 ===================\n")
continue
cursor.close()
except:
print(" ============================第", str(num),"条 其他未知错误 ===================\n")
except:
print(" ============================第", str(num),"条 其他未知错误 ===================\n")
# 设置开启多少线程,双层循环,最外层控制循环倍数
def Go():
start = 1
stop = 0
for x in range(0, 1):
for t in range(0, 30):
stop = stop + 200
thread = threading.Thread(target = Main, args = (start, stop))
thread.start()
print(" ==========================第", str(t + 1),"线程开启成功====================\n")
start = start + 200
Go()
# Login_Session.py
# _*_ coding: utf-8 _*_
"""
本程序于2019-06-25开发
开发者:WYang
核心功能:
1.批量登录微博账号并返回cookie和uid
2.自动检测是否登录成功,如果失败则程序登录直到登录成功为止
3.正在开发中
日志:
1.2019-06-27核心功能已经开发完毕
2.2019-06-28新增调用接口,调用本函数直接给出账号参数就可以,参数类型为list
3.2019-06-30所有基础功能已经开发完毕,优化日志输出模式,添加注释
"""
import re
import rsa
import time
import json
import base64
import random
import logging
import binascii
import requests
import urllib.parse
from pytesser import *
import sys
sys.path.append("../../")
from model.WeiBo.Mode import Get_Data,Post,Send_Content,Conn,User_Agent
#伪造来源IP
def X_Forwarded():
ip=str(random.randint(1,254))+"."+str(random.randint(1,254))+"."+str(random.randint(1,254))+"."+str(random.randint(1,254))
return ip
#微博类,登录微博
class WeiBoLogin(object):
#构造函数
def __init__(self):
user_agent = User_Agent.Main()
self.user_name = None
self.pass_word = None
self.user_uniqueid = None
self.user_nick = None
self.session = requests.Session()
self.session.headers.update({"User-Agent": user_agent})
self.session.get("http://weibo.com/login.php")
return
# 登录微博,返回True或者False
def login(self, user_name, pass_word):
self.user_name = user_name
self.pass_word = pass_word
self.user_uniqueid = None
self.user_nick = None
# 获取Json数据
s_user_name = self.get_username()
json_data = self.get_json_data(su_value = s_user_name)
if not json_data:
return False
s_pass_word = self.get_password(json_data["servertime"], json_data["nonce"], json_data["pubkey"])
#随机分辨率(防封号)
srW = ["1024×100","1024×1280","1024×273","1024×310","1024×480","1024×502","1024×576","1024×600","1024×768","1028×772","1050×1400","1072×1448","1080×1200","1080×1620","1080×1800","1080×1920","1080×2160","1080×2244","1080×2246","1080×2248","1080×2280","1080×2340","1080×3840","1152×1920","1152×768","1200×1200","1200×1600","1200×1920","1200×280","1200×800","1200×825","1200×900","1216×2160","1280×1024","1280×120","1280×1920","1280×240","1280×242","1280×248","1280×256","1280×272","1280×320","1280×370","1280×390","1280×400","1280×420","1280×422","1280×480","1280×505","1280×512","1280×540","1280×600","1280×645","1280×720","1280×768","1280×800","1280×854","1280×960","1284×804","1312×2560","1320×2736","1365×768","1366×1024","1366×148","1366×159","1366×232","1366×238","1366×249","1366×254","1366×256","1366×374","1366×378","1366×384","1366×400","1366×415","1366×419","1366×475","1366×768","1366×800","1400×1050","1404×1872","1440×1080","1440×1440","1440×1600","1440×1700","1440×1920","1440×2560","1440×2880","1440×540","1440×900","1440×960","1536×2048","1536×2560","1600×1024","1600×1200","1600×2560","1600×400","1600×480","1600×768","1600×900","1604×1204","1680×1050","1680×340","1680×342","1680×472","1680×945","1792×768","1920×108","1920×1080","1920×1200","1920×1280","1920×132","1920×158","1920×165","1920×177","1920×1920","1920×200","1920×210","1920×232","1920×238","1920×245","1920×264","1920×270","1920×284","1920×290","1920×317","1920×340","1920×358","1920×360","1920×378","1920×388","1920×400","1920×457","1920×480","1920×486","1920×502","1920×510","1920×520","1920×530","1920×540","1920×550","1920×560","1920×570","1920×60","1920×624","1920×663","1920×687","1920×708","1920×710","1920×720","1920×760","1920×780","1924×1024","2048×1152","2048×1536","2048×1556","2048×2048","2048×2560","2160×1440","2160×2880","2160×3840","2200×1650","2400×1600","2560×1080","2560×1440","2560×1600","2560×1616","2560×1700","2560×2048","2560×480","2732×2048","2736×1824","2800×2100","2880×158","2880×1620","2880×1800","2880×1920","3000×2000","3200×1800","3240×2160","3280×2048","3440×1440","360×360","360×400","360×480","360×600","360×640","383×234","384×220","384×234","3840×1080","3840×1491","3840×160","3840×1600","3840×2160","3840×600","3840×698","3840×720","3840×940","3840×998","390×390","394×509","400×234","400×240","400×300","400×400","400×96","4096×2160","4096×2304","4096×2560","428×240","448×128","454×454","466×350","479×234","479×240","480×1024","480×1120","480×128","480×160","480×210","480×220","480×234","480×240","480×272","480×290","480×320","480×360","480×468","480×480","480×60","480×640","480×720","480×800","480×854","480×960","490×240","492×240","502×240","512×128","512×256","5120×1440","5120×2160","5120×2880","520×288","528×220","536×328","540×1132","540×540","540×960","552×256","557×234","558×234","560×220","560×240","560×400","580×54","600×1024","600×234","600×448","600×600","600×800","640×1136","640×128","640×1280","640×1360","640×200","640×220","640×234","640×240","640×320","640×350","640×360","640×400","640×468","640×480","640×640","640×960","719×234","720×1280","720×1440","720×1498","720×1500","720×1520","720×1528","720×1920","720×240","720×272","720×400","720×480","720×672","720×720","750×1334","758×1024","760×400","768×1024","768×128","768×1280","768×768","7680×4320","800×1280","800×256","800×280","800×300","800×320","800×480","800×600","800×800","800×92","820×1024","822×260","840×480","852×480","852×600","854×480","862×240","880×228","882×228","888×408","900×1440","920×234","920×920","959×320","960×1280","960×160","960×480","960×540","960×544","960×960"]
# 构建POST参数,用于提交请求时用到的参数
post_data = {
"entry": "weibo",
"gateway": "1",
"from": "",
"savestate": "7",
"userticket": "1",
"vsnf": "1",
"service": "miniblog",
"encoding": "UTF-8",
"pwencode": "rsa2",
"sr": random.choice(srW),
"prelt": "529",
"url": "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack",
"rsakv": json_data["rsakv"],
"servertime": json_data["servertime"],
"nonce": json_data["nonce"],
"su": s_user_name,
"sp": s_pass_word,
"returntype": "TEXT",
}
# 获取验证码 captcha 图片代码,并打开 //后期加载API接口实现自动识别或者自主开发人工智能识别接口
if json_data["showpin"] == 1:
url = "http://login.sina.com.cn/cgi/pin.php?r=%d&s=0&p=%s" % (int(time.time()), json_data["pcid"])
with open("captcha.jpeg", "wb") as file_out:
file_out.write(self.session.get(url).content)
dir = 'captcha.jpeg'
img = Image.open(dir)
img.show()
code = input("请输入验证码:")
post_data["pcid"] = json_data["pcid"]
post_data["door"] = code
# 登录微博
Pan = True#用于判断是否登录成功,不成功一直循环
while Pan:
try:
login_url_1 = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&_=%d" % int(time.time())
json_data_1 = self.session.post(login_url_1, data = post_data).json()
if json_data_1["retcode"] == "0":
params = {
"callback": "sinaSSOController.callbackLoginStatus",
"client": "ssologin.js(v1.4.18)",
"ticket": json_data_1["ticket"],
"ssosavestate": int(time.time()),
"_": int(time.time() * 1000),
}
response = self.session.get("https://passport.weibo.com/wbsso/login", params = params)
json_data_2 = json.loads(re.search(r"\((?P
.*)\)", response.text).group("result"))
if json_data_2["result"] is True:
self.user_uniqueid = json_data_2["userinfo"]["uniqueid"]
self.user_nick = json_data_2["userinfo"]["displayname"]
logging.warning("微博登录 成功!!: %s", json_data_2)
else:
pass
logging.warning("微博登录 错误: %s", json_data_2)
else:
pass
# logging.warning("微博登录 错误: %s", json_data_1)
return True if self.user_uniqueid and self.user_nick else False
except:
print("==============错误!无返回数据!2秒后尝试重新登录该账号==========")
time.sleep(2)
#获取加密后密码
def get_password(self, servertime, nonce, pubkey):
string = (str(servertime) + "\t" + str(nonce) + "\n" + str(self.pass_word)).encode("utf-8")
public_key = rsa.PublicKey(int(pubkey, 16), int("10001", 16))
password = rsa.encrypt(string, public_key)
password = binascii.b2a_hex(password)
return password.decode()
#获取合法、加密用户名
def get_username(self):
username_quote = urllib.parse.quote_plus(self.user_name)
username_base64 = base64.b64encode(username_quote.encode("utf-8"))
return username_base64.decode("utf-8")
#获取Json数据,包括servertime,nonce,nonce,rsakv,showpin
def get_json_data(self, su_value):
params = {
"entry": "weibo",
"callback": "sinaSSOController.preloginCallBack",
"rsakt": "mod",
"checkpin": "1",
"client": "ssologin.js(v1.4.18)",
"su": su_value,
"_": int(time.time() * 1000),
}
try:
response = self.session.get("http://login.sina.com.cn/sso/prelogin.php", params = params)
json_data = json.loads(re.search(r"\((?P
.*)\)", response.text).group("data"))
except Exception as excep:
json_data = {}
# logging.error("微博登录 获取Json数据错误: %s", excep)
# logging.debug("微博登录 获取Json数据: %s", json_data)
return json_data
# 主函数,提交登录验证获取多个账号的uid和cookie,返回list
def Main(Account):
print("")
print("================================登录开始,共",str(len(Account)),"个账号================================")
print("")
Return_Data = []
PanDuan=True
db = Conn.GetConn()
cur = db.cursor()
del_sql = "delete from cookies"
cur.execute(del_sql)
db.commit()
while PanDuan:
for x in range(0, int(len(Account))): # 用账号列表的长度来确定循环多少次
logging.basicConfig(level = logging.DEBUG, format = "%(asctime)s\t%(levelname)s\t%(message)s")
weibo = WeiBoLogin()
P = True
while P:
P = weibo.login(Account[x], "Admin141..")
if P == True:
print("==========================第",str(x+1),"个账号登录成功===========================")
cook = requests.utils.dict_from_cookiejar(weibo.session.cookies)
uid = str(re.findall(r"uid=(.+?)&vf",urllib.parse.unquote(str(cook)).encode('utf-8', 'replace').decode('gbk','replace'))).replace("['", "").replace("']", "")
cook = str(cook).replace('\'', "").replace(':', '=').replace(',', ";").replace(' ', '').replace('{','').replace('}', '')
Return_Data = str(cook + "____________" + uid)
sql = """insert into cookies(cookies) value ('%s')""" % (str(Return_Data))
cur.execute(sql)
db.commit()
P = False
else:
print("===========================登录失败===========================")
if x == int(len(Account)):
db.close()
break
print("")
print("")
# print(Return_Data[cokk])#输出保存的cookie
print(" =============================================================")
print(" || ||")
print(" || 写数据库成功 ||")
print(" || 登录程序结束 ||")
print(" || ||")
print(" || ||")
print(" =============================================================")
return Return_Data
# if __name__=="__main__":
# Account = Account_Read.Main()
# Send_Content.py
# _*_ coding: utf-8 _*_
import os
import requests
import urllib.parse
import random
import time
import re
import sys
sys.path.append("../../")
from model.WeiBo.Mode import Get_Data,Conn,User_Agent
def Url():
url = "https://www.weibo.com/p/aj/v6/mblog/add?ajwvr=6&domain=100505&__rnd=" + str(int(round(time.time() * 1000)))
return url
def Head(cook):
user_agent = User_Agent.Main()
header = {
"authority": "www.weibo.com",
"method": "POST",
"path": "/p/aj/v6/mblog/add?ajwvr=6&domain=100505&__rnd=" + str(int(round(time.time() * 1000))),
"scheme": "https",
"accept": "*/*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh,zh-CN;q=0.9",
"content-length": "328",
"content-type": "application/x-www-form-urlencoded",
"cookie": cook,
"origin": "https://www.weibo.com",
"referer": "https://www.weibo.com/p/1005057211283013/home?from=page_100505&mod=TAB&is_all=1",
"user-agent": user_agent,
"x-requested-with": "XMLHttpRequest",
}
return header
def Post_Data(num):
strt = "文学大家系列之第"+str(num)+"篇"
content_title = urllib.parse.quote(strt)
text = Get_Data.Wen_Zhang_Content()
data = {
"content":content_title,
"location": "page_100505_home",
"text": text,
"appkey": "",
"style_type": "1",
"pic_id": "",
"tid": "",
"pdetail": "",
"mid": "",
"isReEdit": "false",
"rank": "0",
"rankid": "",
"pub_source": "page_2",
"topic_id": "1022:",
"pub_type": "dialog",
"_t": "0",
}
return data
#获取cookies
def Cook():
cookies = []
T = True
while T:
try:
db = Conn.GetConn()
cur = db.cursor()
sql = "select * from cookies"
cur.execute(sql)
res = cur.fetchall()
for row in res:
cookies.append(row[1])
db.commit()
db.close()
T = False
return cookies
except:
print(" ===================获取Cookies错误,正在重新获取===============\n")
def Start():
cookies = Cook()
uid = []
cook = []
url = Url()
for c in range(0, int(len(cookies))): # 提取cookies和uid并添加到列表
uid.append(str(re.findall(r"____________(..........+?)", str(cookies[c]))).replace("['", "").replace("']", ""))
cook.append(str(re.findall(r"(.+?)____________", str(cookies[c]))).replace("['", "").replace("']", ""))
try:
for cok in range(0, int(len(cookies))): # 每个账号的循环
num = 1
cook_use = cook[cok]
nu = random.randint(1,100000)
hander = Head(cook_use) # 获取每次提交的请求头
post_data = Post_Data(nu) # 获取每次提交的Post内容
while True:
resp = requests.post(url, post_data, headers = hander) # 提交
if "100000" in resp.text:
print("第", cok + 1, "个账号发布微博,成功")
print("标题:", urllib.parse.unquote(str(post_data["content"])))
print("内容:", str(post_data["text"]))
break
elif "100001" in resp.text:
print("失败,原因:", urllib.parse.unquote(resp.text))
num = num + 1
if num > 5:
print("失败次数超过5次!!")
continue
elif "10002" in resp.text:
print("失败,原因:服务暂停")
num = num + 1
if num > 5:
print("失败次数超过5次!")
continue
else:
print("失败,原因:未知错误,2秒后继续",urllib.parse.unquote(resp.text))
num = num + 1
time.sleep(3)
continue
except:
# print(Exception.e)
print("错误")
# def Main():
# Post_Data()
# User_Agent.py
import os
import sys
import io
import random
def Main():
User_Agent = [
"MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1)",
"Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1)",
"Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;Trident/4.0;SE2.XMetaSr1.0;SE2.XMetaSr1.0;.NETCLR2.0.50727;SE2.XMetaSr1.0)"
"Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
"Mozilla/5.0 (Linux; U; Android 2.2.1; zh-cn; HTC_Wildfire_A3333 Build/FRG83D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50",
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER) ",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
"Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
"Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
"Mozilla/5.0(Macintosh;IntelMacOSX10.6;rv:2.0.1)Gecko/20100101Firefox/4.0.1",
"Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11",
"NOKIA5700/ UCWEB7.0.2.37/28/999",
"Openwave/ UCWEB7.0.2.37/28/999",
"Opera/8.0 (Windows NT 5.1; U; en)",
"Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
"Opera/9.80(WindowsNT6.1;U;en)Presto/2.8.131Version/11.11",
"UCWEB7.0.2.37/28/999",
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60',
'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;',
'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11'
]
data = random.choice(User_Agent)
return data
# if __name__ == '__main__':
# print(Main())
四个号全挂了......