主要过程是
1.浏览器打开百度首页
2.点击右上角登录按钮
3.弹出登录框 .默认是扫码登录所以还要再点击登录按钮
4.点击登录按钮之后出现输入用户名、密码的框 加入用户名密码值
5.输入完点击登录
(主要在查找元素的方法
https://selenium-python-zh.readthedocs.io/en/latest/locating-elements.html)
from selenium import webdriver
from datetime import datetime
import time
#1.
browser = webdriver.Chrome()
strUrl ="http://www.baidu.com"
browser.get(strUrl)
#2.
search_btn = browser.find_element_by_xpath("/html/body/div/div/div/a[@class='s-top-login-btn c-btn c-btn-primary c-btn-mini lb']")
search_btn.click()
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(1)
#3.
search_btnLog = browser.find_element_by_id("TANGRAM__PSP_11__footerULoginBtn")
search_btnLog.click()
time.sleep(1)
#4.
search_input = browser.find_element_by_id("TANGRAM__PSP_11__userName")# 获取到百度登录输入用户名框
search_input.send_keys("********")
search_psw = browser.find_element_by_id("TANGRAM__PSP_11__password")# 获取到百度登录输入密码框
search_psw.send_keys("*********")
#5.
search_Btn = browser.find_element_by_id("TANGRAM__PSP_11__submit")# 获取到百度登录按钮
search_Btn.click()
time.sleep(1)主要是因为点击之后 网页还得在加载 不会立刻就能找到元素
现在的小缺陷就是百度登录之后会要求验证
所以一系列流程走下来还是要再验证下
下次可以试试直接用cookie绕过验证
死等1s有点傻
还好 selenium有显示等待
优化了下代码
from selenium import webdriverfrom
selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
browser = webdriver.Chrome()
strUrl ="http://www.baidu.com"
browser.get(strUrl)
print("1:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
try:
element = WebDriverWait(browser,10).until(
EC.presence_of_element_located((By.XPATH,"/html/body/div/div/div/a[@class='s-top-login-btn c-btn c-btn-primary c-btn-mini lb']"))
)
element.click()
print("点击了右上角登录按钮:",datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
finally:
print("搜索右上角登录按钮完成",datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
try:
elementL = WebDriverWait(browser,10).until(
EC.presence_of_element_located((By.ID,'TANGRAM__PSP_11__footerULoginBtn'))
)
elementL.click()
print("点击了弹窗的登录按钮:",datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
finally:
print("搜索点击登录弹窗按钮完成",datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
try:
elementInput = WebDriverWait(browser,10).until(
EC.presence_of_element_located((By.ID,'TANGRAM__PSP_11__userName'))
)
elementInput.send_keys("******")
search_psw = browser.find_element_by_id("TANGRAM__PSP_11__password")# 获取到百度搜索框
search_psw.send_keys("******")
search_Btn = browser.find_element_by_id("TANGRAM__PSP_11__submit")# 获取到百度搜索框
search_Btn.click()
print("输入用户名密码完成:",datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
finally:
print("搜索输入用户名密码完成")
输出的log
1: 2020-05-25 16:50:05
点击了右上角登录按钮: 2020-05-25 16:50:05
搜索右上角登录按钮完成 2020-05-25 16:50:05
点击了弹窗的登录按钮: 2020-05-25 16:50:06
搜索点击登录弹窗按钮完成 2020-05-25 16:50:06
输入用户名密码完成: 2020-05-25 16:50:06
搜索输入用户名密码完成
嗯呢 超级快
selenium显式等待
https://selenium-python-zh.readthedocs.io/en/latest/waits.html
网友评论