1、实现自动化登录某个页面,需要输入用户名和密码认证,导入模块和库
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.chrome.options import Options import re import subprocess import time
2、设置Chrome浏览器跳过安全检查
chrome_options = Options() chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--ignore-ssl-errors')
3、设置Chrome浏览器禁止证书检查
capabilities = DesiredCapabilities.CHROME.copy() capabilities['acceptInsecureCerts'] = True
4、使用Chrome WebDriver实例化WebDriver对象,并传入Chrome选项和DesiredCapabilities,启动Chrome浏览器并打开登录页面
driver = webdriver.Chrome(options=chrome_options, desired_capabilities=capabilities) # 启动Chrome浏览器并打开登录页面 driver.get("https://www.baidu.com/") #输入需要登录的地址
5、找到用户名和密码输入框并输入用户名和密码,其中"user_name"和"password"分别为登录页面用户名和密码输入框对应的id或name,该值通过开发者页面获取(按F12进入)。"user1"和"123456"分别为自定义的用户名和密码。
username_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "user_name"))) username_input.send_keys("user1") time.sleep(1) password_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "password"))) password_input.send_keys("123456") time.sleep(1)
6、找到登录按钮并点击
login_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "loginbtn"))) login_button.click() time.sleep(3)
7、好了,附上完整源代码
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.chrome.options import Options import re import subprocess import time # 设置Chrome浏览器跳过安全检查 chrome_options = Options() chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--ignore-ssl-errors') # 设置Chrome浏览器禁止证书检查 capabilities = DesiredCapabilities.CHROME.copy() capabilities['acceptInsecureCerts'] = True driver = webdriver.Chrome(options=chrome_options, desired_capabilities=capabilities) # 启动Chrome浏览器并打开登录页面 driver.get("https://www.baidu.com/") time.sleep(3) # 找到用户名和密码输入框并输入用户名和密码 username_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "user_name"))) username_input.send_keys("user1") time.sleep(1) password_input = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "password"))) password_input.send_keys("123456") time.sleep(1) # 找到登录按钮并点击 login_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "loginbtn"))) login_button.click() time.sleep(3)