PythonLog171209
2017-12-09 本文已影响0人
迟客
本周开始Python web方向的知识。以下是模拟登录研究生教务系统,并获取课表的Python代码。
获取cookie
from selenium import webdriver
from time import sleep
import requests
chromePath = r'G:\\code_py\\tool\\chromedriver.exe'
wd = webdriver.Chrome(executable_path= chromePath)
loginUrl = 'http://yjspy.nwafu.edu.cn/index.do'
username = input('学号:')
password = input('密码:')
wd.get(loginUrl)
wd.find_element_by_xpath('//*[@id="login"]/form/table/tbody/tr[1]/td/input').send_keys(username)
wd.find_element_by_xpath('//*[@id="pwd"]').send_keys(password)
sleep(10)#手动输入验证码
wd.find_element_by_xpath('//*[@id="login"]/form/div/input[1]').click() #若是按钮
req = requests.Session() #构建Session
cookies = wd.get_cookies()#直接使用
for cookie in cookies:
req.cookies.set(cookie['name'],cookie['value'])
cookie = open('cookie.txt',"w")
cookie.write(str(cookies))
cookie.close()
模拟登陆获取课表
# -*- coding: UTF-8 -*-
from urllib import request
from urllib import error
from urllib import parse
from PIL import Image
from http import cookiejar
from bs4 import BeautifulSoup
import webbrowser
if __name__ == '__main__':
#声明一个CookieJar对象实例来保存cookie
cookie = cookiejar.CookieJar()
#利用urllib.request库的HTTPCookieProcessor对象来创建cookie处理器,也就CookieHandler
cookie_support = request.HTTPCookieProcessor(cookie)
#通过CookieHandler创建opener
opener = request.build_opener(cookie_support)
#登陆地址
login_url = 'http://yjspy.nwafu.edu.cn/j_acegi_security_check '
#User-Agent信息
user_agent = r'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
#Headers信息
head = {'User-Agnet': user_agent, 'Connection': 'keep-alive'}
username = input('学号:') #输入学号
password = input('密码:') #输入密码
while True:
CaptchaUrl = 'http://yjspy.nwafu.edu.cn/getCaptcha.do'
picture = opener.open(CaptchaUrl).read()
# 用openr访问验证码地址,获取cookie
local = open('G:/code_py/yjsjw/image.jpg', 'wb')
local.write(picture)
local.close()
#打开图片
img=Image.open('image.jpg')
img.show()
# 保存验证码到本地
captcha = input('输入验证码:')
refresh = input('是否刷新 y or n:')
if refresh == 'n' or None:
break
#登陆Form_Data信息
Login_Data = {}
Login_Data['j_username'] = username
Login_Data['j_password'] = password
Login_Data['j_captcha'] = captcha
Login_Data['groupId'] = ''
#使用urlencode方法转换标准格式
logingpostdata = parse.urlencode(Login_Data).encode('utf-8')
#创建Request对象
req1 = request.Request(url=login_url, data=logingpostdata, headers=head)
#面向对象地址
date_url = 'http://yjspy.nwafu.edu.cn/studentschedule/showStudentSchedule.do?groupId=&moduleId=20101'
#面向对象
Date_Data = {}
Date_Data['groupId'] = ''
Date_Data['moduleId'] = '20101'
#使用urlencode方法转换标准格式
datepostdata = parse.urlencode(Date_Data).encode('utf-8')
req2 = request.Request(url=date_url, data=datepostdata, headers=head)
try:
#使用自己创建的opener的open方法
response1 = opener.open(req1)
response2 = opener.open(req2)
htmlpage = response2.read().decode('utf-8')
soup = BeautifulSoup(htmlpage, 'html.parser')
table = soup.select('#print')[0]
title = '<meta charset="GB2312"> <!-- for HTML5 -->'+'\n'+'<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />'
#打印查询结果
table = str(table) + title
f = open('table.html','w',encoding = 'utf-8')
f.write(str(table))
f.close()
url = 'table.html'
webbrowser.open(url)
except error.URLError as e:
if hasattr(e, 'code'):
print("HTTPError:%d" % e.code)
elif hasattr(e, 'reason'):
print("URLError:%s" % e.reason)
下周打算看看web框架,主要是Django。
以上。