遍历hao123中某一区域的所有链接,点击每个链接时,会打开新的窗口,获取新窗口的title后关闭窗口,切换到初始窗口继续打开下一个链接
代码如下:
#coding=utf-8 from selenium import webdriver import time base_url = "http://www.hao123.com" driver = webdriver.Firefox() driver.get(base_url) handle_hao123 = driver.current_window_handle s = driver.find_elements_by_css_selector("ul.js_bd.site-bd.site-hd0>li>a") for i in s: i.click() all_handles = driver.window_handles #切换到新打开的窗口 for handle in all_handles: if handle != handle_hao123: driver.switch_to.window(handle) print driver.title #关闭新窗口 driver.close() #切换到初始窗口 driver.switch_to.window(handle_hao123) #为了表示最后回到初始窗口再加一个打印 print driver.title,driver.current_url driver.close()
不妥之处请指正
时间: 2024-10-23 13:10:00