selenium的窗口切换

如何进入到新窗口进行提取?
web.switch_to.window(web.window_handles[-1])

关掉子窗口
web.close()

变更selenium窗口,回到原来的窗口
web.switch_to.window(web.window_handles[0])

实例

import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys

web = Chrome()

web.get("http://lagou.com")

web.find_element_by_xpath('//*[@id="cboxClose"]').click()

time.sleep(1)

web.find_element_by_xpath('//*[@id="search_input"]').send_keys('python',Keys.ENTER)

web.find_element_by_xpath('//*[@id="jobList"]/div[1]/div[1]/div[1]/div[1]/div[1]/a').click()

time.sleep(1)

# 如何进入到新窗口进行提取?
# 注意: 在selenium眼中,仍然是原来的页面,并没有跳转到新的窗口
web.switch_to.window(web.window_handles[-1])    # 对应的是最后一个窗口

# 在新窗口中提取内容
job_detial = web.find_element_by_xpath('//*[@id="job_detail"]/dd[2]/div').text
print(job_detial)

# 关掉子窗口
web.close()

# 变更selenium窗口,回到原来的窗口
web.switch_to.window(web.window_handles[0]) # 对应的是第一个窗口


版权声明:本文为m0_56600567原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。