fromselenium import webdriverfromselenium.webdriver.chrome.options import Optionsfromselenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions asECfromselenium.webdriver.common.by import Byfromselenium.webdriver.common.action_chains import ActionChains
import timefromimage_match import distancefromimage_match import get_tracksfromimage_match import getSlideInstanceclass yiDundriver(object):
def __init__(self, url, prt='', time2wait=10):
ex_path= 'C:\Program Files\Google\Chrome\Application\chromedriver.exe'chrome_options=Options()
# chrome_options.add_argument("--proxy-server=http://%s" %prt)
chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('disable-infobars')
self.browser= webdriver.Chrome(executable_path= ex_path, chrome_options=chrome_options)
self.browser.set_window_size(500,800)
self.browser.implicitly_wait(10)
self.browser.get(url)
self.wait=WebDriverWait(self.browser, time2wait)
def __clickVerifyBtn(self):
verify_btn= self.wait.until(EC.element_to_be_clickable((By.ID, "btnCertificationpone")))
verify_btn.click()
def __slideVerifyCode(self):
slider= self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'yidun_slider')))
ActionChains(self.browser).click_and_hold(slider).perform()
slider_loc_x= slider.location["x"]
img= self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "yidun_bg-img")))
icon= self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "yidun_jigsaw")))
pic_width= img.size['width']
icon_width= icon.size['width']
img_tags= self.browser.find_elements_by_tag_name("img")
img_url= img_tags[0].get_attribute("src")
icon_url= img_tags[1].get_attribute("src")
match_x=distance(img_url, icon_url, pic_width)if match_x == -1:
raise Exception()
slider_instance=getSlideInstance(pic_width, icon_width, match_x)
tracks=get_tracks(slider_instance)for track intracks:
ActionChains(self.browser).move_by_offset(xoffset=track, yoffset=0).perform()else:
ActionChains(self.browser).move_by_offset(xoffset=3, yoffset=0).perform()
ActionChains(self.browser).move_by_offset(xoffset=-3, yoffset=0).perform()
time.sleep(0.5)
ActionChains(self.browser).release().perform()
time.sleep(3)
cur_loc_x= slider.location["x"]if cur_loc_x >slider_loc_x:
print("success")returnTrueelse:returnFalse
def verifySlideCode(self,attempt_times=10):
#尝试attempt_times次滑动验证,返回是否验证通过
self.wait.until(EC.text_to_be_present_in_element((By.CLASS_NAME,"yidun_tips__text"), r"向右拖动滑块填充拼图"))for attempt inrange(attempt_times):try:ifself.__slideVerifyCode():returnTrue
except Exceptionase:
print(e)
ActionChains(self.browser).release().perform()
refresh= self.wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "yidun_refresh")))
refresh.click()
time.sleep(0.6)returnFalseif __name__ == '__main__':
drv= yiDundriver('http://dun.163.com/trial/jigsaw-wap')
drv.verifySlideCode()