这篇是对上次写的优化。步骤可以看上篇的,这个我就直接上代码了。
import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import ActionChains
#输入账号密码
from PW.mm import USER, WORD
def logins():
#用户名
user=wait.until(EC.presence_of_element_located((By.ID,'J-userName')))
#密码
password=wait.until(EC.presence_of_element_located((By.ID,'J-password')))
user.send_keys(USER)
password.send_keys(WORD)
#登录
btn=wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'login-btn')))
btn.click()
#滑块验证
def verify():
x=340
#获取滑块
block=wait.until(EC.presence_of_element_located((By.ID,'nc_1_n1z')))
ActionChains(driver).drag_and_drop_by_offset(block,xoffset=x,yoffset=15).perform()
#获取cookies
def cookies():
with open('12306_cookies.txt', 'w+', encoding='utf-8')as f:
for i in driver.get_cookies():
if i:
f.write(json.dumps(i) + '\n')
driver=webdriver.Chrome()
#反屏蔽
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
})
wait=WebDriverWait(driver,10)
driver.maximize_window()
#找到登录
def page_login(url):
driver.get(url)
#找到登录元素
login=wait.until(EC.presence_of_element_located((By.ID,'J-btn-login')))
login.click()
time.sleep(3)
logins()
verify()
#点掉提示框
wait.until(EC.presence_of_element_located((By.CLASS_NAME,'modal-close'))).click()
cookies()
if __name__ == '__main__':
url='https://www.12306.cn/index/'
driver=page_login(url)
。。。这个是selenium的如果你没学过的话,自己去了解下,这个运行要谷歌浏览器装个驱动的,这个要装到你的python里,你可以搜下。了解了解
http://chromedriver.storage.googleapis.com/index.html
驱动链接我放在上面了。
那就到此介绍了!!!
文章评论