之前公司的验证码比较简单,可以采取直接破解的方式进行登录
部分代码如下:
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Selectimport unittest,time,re,sys from PIL import Image import pytesseract reload(sys) sys.setdefaultencoding(‘utf-8‘) class Ypt(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(30) self.base_url = "http://*********.com" self.verificationErrors = [] self.accept_next_alert = True def get_streen(self): driver = self.driver driver.save_screenshot(‘D://aa.png‘) #截取当前网页,该网页有我们需要的验证码 imgelement = driver.find_element_by_xpath(‘//*[@id="id_checkCode"]‘) #定位验证码 location = imgelement.location #获取验证码x,y轴坐标 size=imgelement.size #获取验证码的长宽 rangle=(int(location[‘x‘]),int(location[‘y‘]),int(location[‘x‘]+size[‘width‘]),int(location[‘y‘]+size[‘height‘])) #写成我们需要截取的位置坐标 i=Image.open("D://aa.png") #打开截图 frame4=i.crop(rangle) #使用Image的crop函数,从截图中再次截取我们需要的区域 frame4.save(‘D://frame4.png‘) img = Image.open(‘D://frame4.png‘) print img.load() aa = .image_to_string(img) print u"识别的验证码为:" print aa if aa == "": #如果识别为空,则再一次识别 driver.find_element_by_xpath(‘//*[@id="id_checkCode"]‘).click() self.get_streen() return aa def test_ypt(self): now_time = open("yuheng.txt","a") driver = self.driver driver.maximize_window() driver.get(self.base_url + "/userLoginOut.screen") driver.find_element_by_id("j_username").clear() driver.find_element_by_id("j_username").send_keys("username") driver.find_element_by_id("j_password").clear() driver.find_element_by_id("j_password").send_keys("password") driver.find_element_by_id("id_imgCode").clear() driver.find_element_by_id("id_imgCode").send_keys(self.get_streen()) driver.find_element_by_id("btn-login").click() driver.find_element_by_id("C5A000005").click() driver.find_element_by_link_text(u"概况数据").click() self.assertEqual(u"万里通通用积分云平台-数据中心-数据概况", driver.title) time.sleep(8)def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException, e: return False return Trueif __name__ == "__main__": unittest.main()
时间: 2024-11-05 15:57:06