selenium12306实现模拟登录
时间: 2023-12-04 08:41:46 浏览: 40
以下是使用selenium模拟登录12306的步骤:
1.安装selenium库和浏览器驱动,这里以Chrome浏览器为例。
2.导入selenium库和time库。
3.创建一个Chrome浏览器对象,并设置浏览器窗口大小。
4.使用get()方法打开12306登录页面。
5.使用find_element_by_xpath()方法找到用户名输入框和密码输入框,并使用send_keys()方法输入用户名和密码。
6.使用find_element_by_xpath()方法找到验证码图片,并使用selenium的ActionChains类模拟鼠标操作,将验证码图片拖动到指定位置。
7.使用find_element_by_xpath()方法找到登录按钮,并使用click()方法点击登录按钮。
8.使用time库的sleep()方法等待页面跳转。
9.使用current_url属性获取当前页面的URL,如果URL中包含“login”字符串,则说明登录失败,否则登录成功。
```python
# 导入库
from selenium import webdriver
import time
# 创建浏览器对象
browser = webdriver.Chrome()
browser.set_window_size(1200, 800)
# 打开12306登录页面
browser.get('https://kyfw.12306.cn/otn/resources/login.html')
# 输入用户名和密码
username = browser.find_element_by_xpath('//*[@id="username"]')
password = browser.find_element_by_xpath('//*[@id="password"]')
username.send_keys('your_username')
password.send_keys('your_password')
# 破解验证码
slider = browser.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[1]/canvas')
ActionChains(browser).drag_and_drop_by_offset(slider, 258, 0).perform()
# 点击登录按钮
login_button = browser.find_element_by_xpath('//*[@id="loginSub"]')
login_button.click()
# 等待页面跳转
time.sleep(5)
# 判断是否登录成功
if 'login' in browser.current_url:
print('登录失败')
else:
print('登录成功')
# 关闭浏览器
browser.quit()
```