import urllib.request
import urllib.parse
import http.cookiejar,re
opener = None
# 带Cookie访问
def openurl(parms):
global opener
if opener == None:
#cookie设置
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
ret = opener.open(parms)
return ret
def login_163(**parms):
#初始化
parms_key = ['domain','password','username']
arg = {}
for key in parms_key:
if key in parms:
arg[key] = parms[key]
else:
arg[key] = ''
#获取syscheckcode
pre_login = arg['domain']
html = openurl(pre_login).read().decode('utf-8')
patt = re.compile(r'.*?name=syscheckcode.*?value="(.*?)".*?')
syscheckcode = patt.search(html)
if not syscheckcode:
raise Exception('GET syscheckcode Fail!')
syscheckcode = syscheckcode.group(1)
#登陆
postdata = {
'syscheckcode':syscheckcode,
'password':arg['password'],
'username':arg['username'],
}
postdata = urllib.parse.urlencode(postdata)
postdata = postdata.encode('utf-8')
req = urllib.request.Request(
url= arg['domain'],
data=postdata
)
html = openurl(req).read().decode('utf-8')
thisurl = 'http://reg.163.com/Main.jsp?username=' + arg['username']
html = openurl(thisurl).read().decode('utf-8')
# 获取随机key
thisurl = 'http://entry.mail.163.com/coremail/fcg/ntesdoor2?verifycookie=1&lightweight=1&from=urs'
html = openurl(thisurl).read().decode('utf-8')
patt = re.compile(r'.*[email protected]&sid=(.*?)&from.*?')
sid = patt.search(html);
sid = sid.group(1)
# 获取sid
thisurl = 'http://mail.163.com/js6/main.jsp?sid=' + sid
html = openurl(thisurl).read().decode('utf-8')
thisurl = 'http://mail.163.com/js6/s?sid=' + sid + '&func=mbox:listMessages&topNav_mobileIcon_show=1&TopTabReaderShow=1&TopTabLofterShow=1'
# 获取邮件key --- 可以读取看看,实际上是一个类似xml的表,所有的邮件都在这里,我们需要的是key,这里是抽取的第一封邮件的key
html = openurl(thisurl).read().decode('utf-8')
patt = re.compile(r'.*?name="id">(.*?).*?')
key = patt.search(html);
key = key.group(1)
# 获取邮件内容
thisurl = 'http://mail.163.com/js6/read/readhtml.jsp?mid=' + key
html = openurl(thisurl).read().decode('utf-8')
# 测试输出
print(html)
# 假设返回假,,这个验证可以最后加上
flag = True
#if 'succeedhandle_login' in html:
#flag = True
return flag
# 这里是开始,我懒得缩进了 if __name__ == '__main__':
# 用户名 及 密码
while True:
user = input('input your username:')
pwd = input('input your password:')
if len(user) != 0 and len(pwd) != 0:
break
print('输入错误')
# 测试网站
dom='https://reg.163.com/logins.jsp'
try:
flag = login_163(username=user,password=pwd,domain=dom)
if not flag:
print('读取失败!')
exit(0)
else:
print('读取成功')
except Exception as e:
print('Error:',e)
反正大致过程就是上面那样,,,很标准的 post登陆,之后 163 的页面比较特殊,具体可以自己去试试。
那个key页面是抓包之后找到的,通过那个key就能获得每一封邮件了。