selenium 模拟登陆淘宝网 - 解决登陆滑块的问题

selenium 模拟登陆淘宝网 - 解决登陆滑块的问题_第1张图片
selenium 模拟登陆淘宝网 - 解决登陆滑块的问题_第2张图片


import time

from selenium import webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import  WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

chrome_path = r'C:\chromedriver'

driver = webdriver.Chrome(executable_path=chrome_path)
# 窗口最大化
driver.maximize_window()
wait = WebDriverWait(driver, 10)

# 查询商品
def search_goods(goods_name):
    driver.get('https://www.taobao.com/')
    time.sleep(2)

    wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="q"]')))
    # 搜索框输入查询信息
    driver.find_element_by_xpath('//*[@id="q"]').send_keys(goods_name)
    driver.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()

# 模拟登陆
def login(username,password):
    time.sleep(2)
    # 账号, 密码输入
    driver.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys(username)
    driver.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys(password)
    # 点击搜索
    driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()

    print("拉动滑块!")

    # 定位滑块元素
    wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="nc_1_n1z"]')))
    source = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]')
    # 定义鼠标拖放动作
    ActionChains(driver).drag_and_drop_by_offset(source, 258, 0).perform()
    driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/button').click()

    try:
        wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='site-nav-user']")))
        driver.find_element_by_xpath("//div[@class='site-nav-user']")

        WebDriverWait(driver, 10).until(
            EC.url_to_be('https://s.taobao.com/search?q=%E5%A5%B3%E8%A3%85&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306')
        )

        print("登陆成功!")
    except Exception as e:
        print('登陆失败!',e)

def main():

    search_goods('女装')
    login('python', 'python')


if __name__ == '__main__':
    main()

你可能感兴趣的:(spider,selenium)