from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
# 输入需要请求的地址
driver.get("https://www.baidu.com/")
# 最大化浏览器
driver.maximize_window()
# 获取当前打开的窗口的所有句柄
window = driver.window_handles
print("当前窗口:",driver.current_window_handle)
driver.find_element_by_xpath('//input[@id="kw"]').send_keys("柠檬班")
driver.find_element_by_xpath('//input[@id="su"]').submit()
# 定位元素
webelenment = (By.XPATH,'//div[@tpl="tieba_general"]//a[text()="吧_百度贴吧"]')
# 强制等待
time.sleep(2)
# 显示等待
WebDriverWait(driver,20).until(EC.presence_of_element_located(webelenment))
# 点击操作
driver.find_element_by_xpath('//div[@tpl="tieba_general"]//a[text()="吧_百度贴吧"]').click()
# 判断窗口是否进行切换,判断是否有开启新的窗口
WebDriverWait(driver,20).until(EC.new_window_is_opened(window))
# 再次获取当前浏览器所有的窗口
windows = driver.window_handles
# 进行窗口的切换,找到需要切换的窗口
driver.switch_to.window(windows[-1]) print("切换后的窗口",driver.current_window_handle)
# 点击签到操作
wb = (By.XPATH,'//a[@title="签到"]')
WebDriverWait(driver,20).until(EC.presence_of_element_located(wb)) time.sleep(2)
driver.find_element_by_xpath('//a[@title="签到"]').click()