一、概述
由于百度页面经常更新,因此页面元素,比如class和id会做更新。因此网上大多数文章,直接拿来用,是无法实现登录的。
二、完整代码
![](https://i-blog.csdnimg.cn/blog_migrate/a2b7024cb6a8cccd23244148c90016f0.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/aa7790439652fcf252898472b6dc57b7.gif)
# !/usr/bin/python3 # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import random USERNAME = 'xiao' # 输入账号 PASSWORD = '123456' # 输入密码 # 随机时间,防止过快被检测 seconds = random.randint(2, 5) chrome_driver = r"E:\virtualenv\django\chromedriver.exe" driver = webdriver.Chrome(executable_path=chrome_driver) driver.maximize_window() wait = WebDriverWait(driver, 10) driver.get('https://www.baidu.com') # 打开登录界面 wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#u1 > a.lb'))).click() wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#TANGRAM__PSP_11__footerULoginBtn'))).click() time.sleep(seconds) # 输入账号密码 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#TANGRAM__PSP_11__userName'))).send_keys(USERNAME) time.sleep(seconds) wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#TANGRAM__PSP_11__password'))).send_keys(PASSWORD) time.sleep(seconds) # # 勾选下次自动登录 # wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#TANGRAM__PSP_11__memberPassLabel'))).click() # time.sleep(seconds) # 点击登录按钮 wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#TANGRAM__PSP_11__submit'))).click()
注意:请根据实际情况,修改账号和密码,页面元素的id。
最重要就是chrome_driver,必须要和你的谷歌浏览器版本一致
本文参考链接: