12306验证码

# !user/bin/env python3
# -*-coding: utf-8 -*-
__author__ = '闻名'

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from chaojiying import Chaojiying_Client
import time
from info import username, password

username_chaojiying = 'koukou'
password_chaojiying = '199812'
soft_id_chaojiying = '903600'


class Example12306(object):
    def __init__(self):
        self.url = 'https://kyfw.12306.cn/otn/resources/login.html'
        self.driver = webdriver.Chrome()
        self.wait = WebDriverWait(self.driver, 10)
        self.chaojiying = Chaojiying_Client(username_chaojiying, password_chaojiying, soft_id_chaojiying)
        self.username = username
        self.password = password

    def pre_pare(self):
        self.driver.get(self.url)
        self.driver.maximize_window()
        time.sleep(1)

        login = self.wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[2]/ul/li[2]/a')))
        login.click()
        time.sleep(1)

        user = self.wait.until(EC.presence_of_element_located((By.ID, 'J-userName')))
        user.send_keys(self.username)
        time.sleep(1)

        passwd = self.wait.until(EC.presence_of_element_located((By.ID, 'J-password')))
        passwd.send_keys(self.password)
        time.sleep(1)

    def get_pic(self):
        img = self.driver.find_element_by_id('J-loginImg')
        img.screenshot('12306.jpg')
        time.sleep(1)

    def get_res(self):
        im = open('12306.jpg', 'rb').read()
        res = self.chaojiying.PostPic(im, 9004)
        print(res)
        return res

    def get_and_point(self, res):
        groups = res.get('pic_str').split('|')
        locations = [[int(num) for num in group.split(',')] for group in groups]
        print(locations)
        for location in locations:
            ActionChains(self.driver).move_to_element_with_offset(self.driver.find_element_by_id('J-loginImg'),
                                                                  location[0], location[1]).click().perform()
            time.sleep(1)
        time.sleep(2)

    def submit(self):
        button = self.wait.until(EC.presence_of_element_located((By.ID, 'J-login')))
        button.click()

    def main(self):
        self.pre_pare()
        while 1:
            time.sleep(2)
            self.get_pic()
            res = self.get_res()
            self.get_and_point(res)
            self.submit()
            if '周鸿昊' in self.driver.page_source:
                break


if __name__ == '__main__':
    exmaple = Example12306()
    exmaple.main()

你可能感兴趣的:(爬虫)