主要是获取当前页的window_handles句柄,
from selenium import webdriver
import time
from lxml import etree
import re
driver =webdriver.Chrome(executable_path=r"添加chromedriver的路径")
url="http://www.chinanpo.gov.cn/search/orgcx.html"
driver.get(url)
#获取当前页句柄
h1=driver.window_handles
print('h1=',h1)
driver.implicitly_wait(2)
driver.find_element_by_xpath(r"/html/body/center/div/div[2]/div/form/div[3]/div[2]/div[2]/input[1]").click()
time.sleep(0.5)
driver.find_element_by_xpath(r"/html/body/center/div/div[2]/div/div[1]/span[2]/a").click()
t=driver.page_source()
response=etree.HTML(t)
print(response)
trs=response.xpath(r"//*[@id='mac_data']/table//tr")
for tr in trs:
_id =tr.xpath(r"./td[2]/a/@href")
_id=_id[0].split('(')[-1][:-2] if _id else None
print(_id)
#点击详情页
driver.find_element_by_xpath(r"//*[@id='mac-data']/table//tr[1]/td[2]/a").click()
h2=driver.window_handles #获取句柄
print("h2=",h2)
driver.swltch_to.window(h2[1])
driver.get(driver.current_url+'?orgId={}'.format(_id))
driver.close()#关闭当前句柄
driver.switch_to.window(h2[0])#回到首页