from selenium import webdriver
import time
def browser():
dr = webdriver.Chrome()
url = 'http://www.baidu.com'
dr.maximize_window() # 窗口最大化
# 获取当前句柄
now_handle = dr.current_window_handle # 获取窗口当前句柄
dr.get(url) # 打开网址
dr.find_element_by_id("kw").send_keys('runoob') # 输入搜索的数据
time.sleep(2)
dr.find_element_by_id("su").click() # 点击搜索一下
time.sleep(2)
dr.find_element_by_xpath("//div[@id='1']//a[contains(text(),'-')]").click() # 点击查询数据
time.sleep(2)
all_handles = dr.window_handles # 获取当前所有开启窗口的句柄
for handle in all_handles:
if handle != now_handle: # 获取到与当前窗口不一样的窗口
dr.switch_to.window(handle) # 切换
time.sleep(2)
dr.find_element_by_xpath("//div[@class='codelist codelist-desktop cate3']//h4[contains(text(),'Python')]").click() #点击需要请求的链接
time.sleep(2)
dr.close()
if name == "main":
browser()