参考:
Python3 模拟登录知乎(requests) http://www.jianshu.com/p/787c3f068ac1 涉及验证码,session, cookie等操作
Python3中利用Urllib进行表单数据提交(Get,Post) http://www.voidcn.com/article/p-cjvfmsjw-x.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#! /usr/bin/python3 import logging import urllib import sys import http.cookiejar def getHttpReq(url): logging.debug("初始化Http Request") headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} req = urllib.request.Request(url=url, headers=headers) return req def initCookie(): logging.debug("初始化Cookie") cookie = http.cookiejar.CookieJar() cjhdr = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(cjhdr) def getHtml(url, postdata): logging.debug("获取HTML内容") res = urllib.request.urlopen(getHttpReq(url), postdata) #logging.debug(res.status, res.reason) if (res.status != 200): logging.error("读取URL页面错误") exit() logging.info('成功读取URL页面') return res.read().decode('utf-8') def isLogin(html): #拿到HTML之后,自行判断是否成功 idx = html.find("class=\"rh_login_botton\"") if idx>0: logging.debug(html) return False else: return True def main(): initCookie() url = "http://192.168.0.222:8082/rhcpm//login/check" postdata = urllib.parse.urlencode({"j_sign": "pc", "j_username": "admin", "j_password": "1"}) postdata = postdata.encode("utf-8") html = getHtml(url, postdata) if not isLogin(html): logging.error("登录失败") exit(1) else: logging.info("登录成功") logging.basicConfig(level=logging.DEBUG) if __name__ == '__main__': for i in range(1,100): logging.info("-------------------------------正在登录:"+ str(i)) main() |