下载chrome浏览器的对应版本自动化驱动
查看本机安装的chrome浏览器版本
点击设帮助--------》点击关于chrome---------》查看版本信息
进入驱动下载地址,找到对应驱动版本(大部分对的上就能用)
下载地址: http://npm.taobao.org/mirrors/chromedriver/
下载完成后复制到你电脑安装chrome.exe目录中去。
然后是导入资源包和核心代码。
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
# 判断元素是否存在
def is_element_exist(self, element):
try:
self.find_element_by_xpath(element)
return True
except:
return False
if __name__ == '__main__':
options = webdriver.ChromeOptions()
# 设置为开发者模式,防止网站识别
options.add_experimental_option(
'excludeSwitches', ['enable-automation'])
# 加载驱动程序
browser = webdriver.Chrome(executable_path='C:/Program Files (x86)/Google/Chrome/Application/chrome_driver.exe',
options=options)
# 窗口最大化
browser.maximize_window()
# 进入淘宝登陆页
browser.get('https://login.taobao.com/member/login.jhtml')
# 点击使用账号密码登陆
try:
browser.find_element_by_xpath('//*[@id="J_QRCodeLogin"]/div[5]/a[1]').click()
except:
pass
browser.find_element_by_id("TPL_username_1").clear()
browser.find_element_by_id("TPL_password_1").clear()
# 填入账号密码
browser.find_element_by_class_name("username-field").click()
browser.find_element_by_id("TPL_username_1").send_keys('17783556843')
browser.find_element_by_class_name("pwd-field").click()
browser.find_element_by_id("TPL_password_1").send_keys('zyh520zyh')
time.sleep(1)
# 点击登陆
browser.find_element_by_id("J_SubmitStatic").click()
# 判断是否出现滑块
while True:
if is_element_exist(browser, "//div[@class='site-nav-user']"):
print("登陆成功")
break
else:
time.sleep(2)
if is_element_exist(browser, "//div[@id='nocaptcha']/div/span/a"):
print("刷新滑块")
browser.find_element_by_xpath("//div[@id='nocaptcha']/div/span/a").click()
time.sleep(1)
browser.find_element_by_id("TPL_password_1").clear()
browser.find_element_by_class_name("pwd-field").click()
browser.find_element_by_id("TPL_password_1").send_keys('zyh520zyh')
browser.find_element_by_xpath("//span[@id='nc_1_n1z']").click()
source = browser.find_element_by_id("nc_1_n1t")
ActionChains(browser).drag_and_drop_by_offset(source, 258, 0).perform()
browser.find_element_by_id("J_SubmitStatic").click()
else:
print("拉动滑块")
browser.find_element_by_id("TPL_password_1").clear()
browser.find_element_by_class_name("pwd-field").click()
browser.find_element_by_id("TPL_password_1").send_keys('zyh520zyh')
time.sleep(1)
browser.find_element_by_xpath("//span[@id='nc_1_n1z']").click()
# 定位滑块元素
source = browser.find_element_by_id("nc_1_n1t")
# 定义鼠标拖放动作
ActionChains(browser).drag_and_drop_by_offset(source, 280, 0).perform()
browser.find_element_by_id("J_SubmitStatic").click()