解决滑块验证登录问题和网站禁止selenium操作无法通过验证问题,问题过程如下,亲测有效:
当输入账号密码,点击登录后出现如下滑动解锁框: 此时,完成滑块自动滑动至右边解锁,写个拖动滑块的函数 move_by_offset(),偏移量的确定方法,浏览器开发者模式(F12),找到滑块的元素ID,拖动至最右边,即可看到合适的偏移量,如下图: 确定偏移量,直接上代码 运行后出现如下现象,滑动解锁出错: 解决上面问题,只需执行一句JS代码: ?至此,可实现12306火车票网站,滑块自动登录。 |
废话不多说,直接上完整代码,如下:
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
class trainTicketLogin(object):
def __init__(self):
self.username = 'XXXXXXXX'
self.passwd = 'XXXXXXXX'
self.url = 'https://kyfw.12306.cn/otn/resources/login.html'
self.browser = webdriver.Firefox()
def login(self,url):
self.browser.get(self.url)
# 选择1.账号密码登录
login_method = self.browser.find_element(By.XPATH,'//div[@class="login-box"]/ul/li[1]/a').click()
user = self.browser.find_element(By.ID,'J-userName').send_keys(self.username)
passwd = self.browser.find_element(By.ID,'J-password').send_keys(self.passwd)
# 登录
submit = self.browser.find_element(By.CLASS_NAME,'login-btn').click()
# print(browser.get_cookies())
time.sleep(3)
button = self.browser.find_element(By.XPATH,'//*[@id="nc_1_n1z"]')
self.Verification(button)
def Verification(self,button):
action = ActionChains(self.browser)
# 防止网站禁止selenium
script = 'Object.defineProperty(navigator,"webdriver",{get:()=>undefined,});'
self.browser.execute_script(script)
#鼠标左键按下不放
action.click_and_hold(button).perform()
#需要滑动的偏移量
action.move_by_offset(300,0)
#释放鼠标
action.release().perform()
time.sleep(0.1)
def run(self):
self.login(self.url)
if __name__ == '__main__':
Spider = trainTicketLogin()
Spider.run()
|