获取验证码的网址和post的网址
进入登陆页面,打开开发者工具,刷新页面,找到checkcode.aspk,向网址http://zf.hhit.edu.cn/CheckCode.aspx发送请求,每次返回一个随机的验证码,并且在请求头中还带有cookie的值。
我们先来获取验证及其request中的cookie,并由人工输入
def codecheck(self):
check_url = 'http://zf.hhit.edu.cn/CheckCode.aspx'
response = requests.get(check_url, headers=self.headers)
with open('checkcode.jpg', 'wb') as f:
f.write(response.content)
image = Image.open('./checkcode.jpg')
image.show()
check_code = input('请输入验证码:')
return check_code, requests.utils.dict_from_cookiejar(response.cookies)
然后输入用户名、密码、验证码,点击登陆
找到default2.aspk,可以看到发送的方式是post,而且Status Code: 302 Found,表示是重定向页面,我们发送post请求是向http://zf.hhit.edu.cn/default2.aspx这个页面发送的
翻到最下面找到formdata,这些就是我们要post的数据,记得要点击一下url encode
以下是完整代码
import requests
from PIL import Image
class HDSpider:
def __init__(self):
self.__VIEWSTATE = 'dDwxNTMxMDk5Mzc0Ozs+AdTOwuk1s1dKYN9ZfAssbX8ZnDM='
self.RadioButtonList1 = '%D1%A7%C9%FA'
self.txtUserName = '你的学号'
self.TextBox2 = '你的密码'
self.headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/45.0.2438.3 Safari/537.36", }
def codecheck(self):
check_url = 'http://zf.hhit.edu.cn/CheckCode.aspx'
response = requests.get(check_url, headers=self.headers)
with open('checkcode.jpg', 'wb') as f:
f.write(response.content)
image = Image.open('./checkcode.jpg')
image.show()
check_code = input('请输入验证码:')
return check_code, requests.utils.dict_from_cookiejar(response.cookies)
def login(self):
url = 'http://zf.hhit.edu.cn/default2.aspx'
txtSecretCode, cookies = self.codecheck()
postdata = {'__VIEWSTATE': self.__VIEWSTATE, 'txtUserName': self.txtUserName, 'Textbox1': '',
'TextBox2': self.TextBox2, 'txtSecretCode': txtSecretCode, 'RadioButtonList1': self.RadioButtonList1
, 'Button1': '', 'lbLanguage': '', 'hidPdrs': '', 'hidsc': ''}
request = requests.post(url,cookies=cookies, data=postdata, headers=self.headers)
request.encoding = request.apparent_encoding
print(request.text)
if __name__ == '__main__':
spider = HDSpider()
spider.login()