# Selenium

### test jd

```python
from selenium import webdriver
from selenium.webdriver.common.by import By  # 按照什么方式查找，By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys  # 键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait  # 等待页面加载某些元素
from selenium.webdriver.common.action_chains import ActionChains
import time
import base64
import cv2


def input_login(chrome):
    # 输入用户名
    print('send name')
    input_username_tag = chrome.find_element(By.ID, 'loginname')
    input_username_tag.send_keys('will@qq.com')
    time.sleep(1)

    # 输入密码
    print('send password')
    input_password_tag = chrome.find_element(By.ID, 'nloginpwd')
    input_password_tag.send_keys('123456789')
    time.sleep(1)

    # 点击登陆
    print('click submit')
    input_password_tag = chrome.find_element(By.ID, 'loginsubmit')
    input_password_tag.click()
    time.sleep(1)

def get_CAPTCHA(chrome):
    # 获取验证图片
    CAPTCHA_bg_img_src_base64 = \
    chrome.find_element(By.XPATH, '//div[@class="JDJRV-bigimg"]/img').get_attribute('src').split(',')[1]
    CAPTCHA_bg_img_binary = base64.b64decode(CAPTCHA_bg_img_src_base64)
    with open('CAPTCHA_bg.png', 'wb') as f1:
        f1.write(CAPTCHA_bg_img_binary)

    CAPTCHA_gap_img_src_base64 = \
    chrome.find_element(By.XPATH, '//div[@class="JDJRV-smallimg"]/img').get_attribute('src').split(',')[1]
    CAPTCHA_gap_img_binary = base64.b64decode(CAPTCHA_gap_img_src_base64)
    with open('CAPTCHA_gap.png', 'wb') as f2:
        f2.write(CAPTCHA_gap_img_binary)


def get_CAPTCHA_distance():
    bg = cv2.imread('CAPTCHA_bg.png', 0)
    gap = cv2.imread('CAPTCHA_gap.png', 0)

    res = cv2.matchTemplate(bg, gap, cv2.TM_CCOEFF_NORMED)
    distance = cv2.minMaxLoc(res)[2][0] * 242 / 360    # 242 / 360 为真实渲染比例
    return distance

# 移动图片进行验证
def move_CAPTCHA(chrome, distance):
    CAPTCHA_slide_btn = chrome.find_element(By.XPATH, '//div[@class="JDJRV-slide-inner JDJRV-slide-btn"]')
    ActionChains(chrome).click_and_hold(on_element=CAPTCHA_slide_btn).perform()
    ActionChains(chrome).move_by_offset(xoffset=distance, yoffset=0).perform()
    ActionChains(chrome).release(on_element=CAPTCHA_slide_btn).perform()
    time.sleep(2)


def main():
    chrome = webdriver.Chrome()
    chrome.implicitly_wait(5)
    chrome.get('https://passport.jd.com/uc/login')

    # input登陆
    input_login(chrome)

    # 图片验证码验证
    get_CAPTCHA(chrome)
    distance = get_CAPTCHA_distance()
    move_CAPTCHA(chrome, distance)

    chrome.close()


if __name__ == '__main__':
    main()

```
