shownb / shownb.github.com

shownb.github.io
shownb.github.io
5 stars 1 forks source link

selenium 无头 #44

Open shownb opened 4 years ago

shownb commented 4 years ago

Selenium 调用IEDriverServer打开IE浏览器

参考链接 https://blog.csdn.net/jichuang123/article/details/53008581 大概是:

关于webdriver下载地址 http://selenium-release.storage.googleapis.com/index.html IEDriverServer_x64_3.14.0.zip http://selenium-release.storage.googleapis.com/3.14/IEDriverServer_x64_3.14.0.zip

Selenium XPATH 定位最全总结 https://testerhome.com/topics/20296

屏幕录取 被录取端

# -*- coding:utf-8 -*-
from socket import socket
from threading import Thread
from zlib import compress
from mss import mss

# 截图大小
WIDTH = int(1366 / 1)
HEIGHT = int(768 / 1)

def send_screenshot(conn):
    with mss() as sct:
        rect = {'top': 0, 'left': 0, 'width': WIDTH, 'height': HEIGHT}

        while 'recording':
            img = sct.grab(rect)
            # 压缩等级 (0-9)
            # 并不一定是压缩level越高越好,这里要综合考虑压缩占用时间和网络传输时间
            pixels = compress(img.bgra, 1)
            # 压缩对比
            # level:0 size:4196683
            # level:1 size:248329
            # level:2 size:246512
            # level:9 size:196212
            size = len(pixels)
            size_len = (size.bit_length() + 7) // 8
            conn.send(bytes([size_len]))
            size_bytes = size.to_bytes(size_len, 'big')
            conn.send(size_bytes)
            conn.sendall(pixels)

def main(host='0.0.0.0', port=5000):
    sock = socket()
    sock.bind((host, port))
    try:
        sock.listen(5)
        print('Server started.')

        while 'connected':
            conn, addr = sock.accept()
            print('Client connected IP:', addr)
            thread = Thread(target=send_screenshot, args=(conn,))
            thread.start()
    finally:
        sock.close()

if __name__ == '__main__':
    main()

观看端

from socket import socket
from zlib import decompress
import cv2
import numpy
from PIL import Image

WIDTH = int(1366 / 1)
HEIGHT = int(768 / 1)

def recvall(conn, length):
    buf = b''
    while len(buf) < length:
        data = conn.recv(length - len(buf))
        if not data:
            return data
        buf += data
    return buf

def main(host='10.100.40.52', port=5000):
    watching = True

    sock = socket()
    sock.connect((host, port))
    try:
        while watching:
            size_len = int(sock.recv(1).encode('hex'), 16)
            size = int(sock.recv(size_len).encode('hex'), 16)
            bgra = decompress(recvall(sock, size))
            img = Image.frombytes("RGB", (WIDTH, HEIGHT), bgra, "raw", "BGRX")
            np_ar = numpy.array(img, dtype=numpy.uint8)
            np_ar = numpy.flip(np_ar[:, :, :3], 2)
            cv2.imshow("OpenCV show", np_ar)
            if cv2.waitKey(25) & 0xFF == ord("q"):
                cv2.destroyAllWindows()
                break
    finally:
        sock.close()

if __name__ == '__main__':
    main()
shownb commented 4 years ago

Python+selenium针对wy控件过登录取数据 https://sbcoder.cn/2019/03/21/Python_WY_Spider.html

selenium登录wy,密码控件输入 https://www.cnblogs.com/6min/p/10868825.html

wy安全控件问题 https://www.cnblogs.com/davidwang456/articles/8708479.html

winio install like that https://www.jianshu.com/p/4cb399f31ec9

https://www.cnblogs.com/CoolJayson/p/8880116.html

shownb commented 4 years ago

win7 32安装 https://www.microsoft.com/zh-TW/download/details.aspx?id=47352

pip install pywinio证书有问题。先更新requests, pip install requests

shownb commented 4 years ago
# _*_ coding: utf-8 _*_
import os, sys
import uuid, time
import pytesseract
from selenium import webdriver
from ctypes import windll
from PIL import Image

def tesseract_file(file_path):
        #my_env = {'TESSDATA_PREFIX': r'C:\Program Files\Tesseract-OCR\testdata'}
        image = Image.open(os.path.realpath(file_path))
        result = pytesseract.image_to_string(image)
        return result

def login_abc(param):
        url = 'https://perbank.abchina.com/EbankSite/startup.do'
        ie_driver = 'C:\Program Files\Internet Explorer\IEDriverServer.exe'
        #os.environ["webdriver.ie.driver"] = ie_driver
        browser = webdriver.Ie(ie_driver)
        browser.maximize_window()
        browser.get(url)
        time.sleep(1)

        browser.find_element_by_id('username').send_keys(param['username'])

        #载入DD
        libpath = 'libs/DD81200x32.dll' if sys.platform == 'win32' else 'libs/DD81200x64.32.dll'
        dd_dll = windll.LoadLibrary(libpath)

        vk = {'5': 205, 'c': 503, 'n': 506, 'z': 501, '3': 203, '1': 201, 'd': 403, '0': 210, 'l': 409, '8': 208,
              'w': 302,
              'u': 307, '4': 204, 'e': 303, '[': 311, 'f': 404, 'y': 306, 'x': 502, 'g': 405, 'v': 504, 'r': 304,
              'i': 308,
              'a': 401, 'm': 507, 'h': 406, '.': 509, ',': 508, ']': 312, '/': 510, '6': 206, '2': 202, 'b': 505,
              'k': 408,
              '7': 207, 'q': 301, "'": 411, '\\': 313, 'j': 407, '`': 200, '9': 209, 'p': 310, 'o': 309, 't': 305,
              '-': 211,
              '=': 212, 's': 402, ';': 410}
        #需要组合shift的按键。
        vk2 = {'"': "'", '#': '3', ')': '0', '^': '6', '?': '/', '>': '.', '<': ',', '+': '=', '*': '8', '&': '7',
               '{': '[', '_': '-',
               '|': '\\', '~': '`', ':': ';', '$': '4', '}': ']', '%': '5', '@': '2', '!': '1', '(': '9'}

        def down_up(code):
            dd_dll.DD_key(vk[code], 1)
            dd_dll.DD_key(vk[code], 2)

        def dd(key):
            if i.isupper():
                # 按下抬起 500是shift键码
                dd_dll.DD_key(500, 1)
                down_up(i.lower())
                dd_dll.DD_key(500, 2)

            elif i in '~!@#$%^&*()_+{}|:"<>?':
                dd_dll.DD_key(500, 1)
                down_up(vk2[i])
                dd_dll.DD_key(500, 2)
            else:
                down_up(i)

        img = browser.find_element_by_id('vCode')
        x, y = img.location['x'] + 50, img.location['y'] + 50

        #移动到密码框点击激活
        dd_dll.DD_mov(x, y)
        dd_dll.DD_btn(1)
        time.sleep(1)

        #依次输入密码字符
        for i in param['password']:
            dd(i)
            time.sleep(0.2)

        left, top = img.location['x'], img.location['y']
        width, height = img.size['width'] + left, img.size['height'] + top
        os.makedirs('imgs')
        oldpath = 'imgs/' + str(uuid.uuid1()) + '.png'
        browser.save_screenshot(oldpath)
        oldpic = Image.open(oldpath)
        newpic = oldpic.crop((left, top, width, height))
        picpath = 'imgs/' + str(uuid.uuid1()) + '.png'
        newpic.save(picpath)
        os.remove(oldpath)

        #tesseract可以识别简单的图形验证码
        vcode = tesseract_file(picpath)
        browser.find_element_by_name('code').send_keys(vcode)

        #os.remove(picpath)
        browser.find_element_by_id('logo').click()

        time.sleep(1)
        logerr = browser.find_element_by_class_name('logon-error').text
        print(logerr)

if __name__ == '__main__':
    login_abc({'username':'13311111111', 'password':'123456'})
shownb commented 4 years ago

获取验证码方法 https://blog.devzeng.com/blog/selenium-captcha-recognition.html