如何使用Selenium获取点击弹出窗口的URL并实现页面跳转?
问题:捕获页面模态弹窗内的链接并跳转至目标页面
目标网站:https://tis.nhai.gov.in/tollplazasataglance.aspx?language=en#
场景:点击表格第四列的链接后会弹出页面内模态窗口,需点击窗口中的「More Information」标签,跳转至类似 https://tis.nhai.gov.in/TollInformation.aspx?TollPlazaID=236 的目标页面。现有Selenium代码无法捕获弹窗内的链接信息,需要实现跳转逻辑。
用户现有代码:
from selenium import webdriver driver = webdriver.Firefox() driver.maximize_window() driver.get("https://tis.nhai.gov.in/tollplazasataglance.aspx?language=en#") b = driver.find_element("xpath", '//*[@id="tollList"]/table/tbody/tr[2]/td[4]/a') c = driver.execute_script("arguments[0].click();", b)
解决方案
这里的弹窗是页面内模态框而非新浏览器窗口,无需切换窗口句柄,直接定位模态框内元素即可。关键是添加显式等待确保模态框和目标元素加载完成,避免元素未找到的错误。
完整代码示例
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.maximize_window() wait = WebDriverWait(driver, 10) # 设置10秒超时等待 try: # 打开目标页面 driver.get("https://tis.nhai.gov.in/tollplazasataglance.aspx?language=en#") # 点击表格第二行第四列的链接(触发模态框) toll_link = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="tollList"]/table/tbody/tr[2]/td[4]/a'))) toll_link.click() # 等待模态框加载完成,定位「More Information」标签并点击 more_info_tab = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'More Information'))) more_info_tab.click() # (可选)如果需要获取目标页面的URL,可在点击后获取当前页面URL target_url = driver.current_url print("目标页面URL:", target_url) finally: # 操作完成后关闭浏览器 driver.quit()
关键说明
- 使用
WebDriverWait显式等待元素可点击状态,避免因页面加载延迟导致的NoSuchElementException。 - 模态框属于当前页面DOM的一部分,直接通过
LINK_TEXT或其他定位方式找到「More Information」标签即可。 - 如果需要批量处理多行数据,可循环定位表格中的每一行第四列链接,重复上述点击和跳转逻辑。
内容的提问来源于stack exchange,提问作者Abhi
相关产品推荐
相关产品推荐

