Selenium得到当前页面的URL

本文介绍了一种通过Selenium WebDriver获取当前页面URL的方法。该方法首先确保页面完全加载完成,然后利用WebDriver实例调用getCurrentUrl()方法来获取URL。此外,还提供了一个超时处理机制,当页面加载超过预设时间后会返回一个错误提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

复制代码
    /**
         * getCurrentURL:(get the current page URL address). 

         * @author huchan
         * @param driver  --- the web driver instance
         * @return String ---the url of current page
         * @since JDK 1.6
         */
        public String getCurrentPageURL(){
            String pageurl="";
            JavascriptExecutor je=(JavascriptExecutor) driver;
            final String docstate=(String) je.executeScript("return document.readyState");
            logger.info("Current loading page state is:"+docstate);
            WebDriverWait wait=new WebDriverWait(driver,120);
            ExpectedCondition<Boolean> ec = new ExpectedCondition<Boolean>() {
                  @Override
                public Boolean apply(WebDriver d) {
                    return (docstate.equals("complete"));
                  }
                };
            try{
               logger.info("We just wait for the current page load correctly now...");
               wait.until(ec);           
               pageurl=driver.getCurrentUrl();
               logger.info("we found the current url is:"+pageurl);
            }
            catch(TimeoutException e){
                pageurl="time out:120 seconds";
                logger.error("Sorry the page cannot be loaded correctly:"+e.getMessage()+driver.getCurrentUrl());
            }
            return pageurl;
        }
复制代码

不多说,代码如上。关键点是一定要等待页面加载完成了再使用driver.getCurrentUrl()方法,否则的话可能得到的页面URL 不正确。



本文转自hcy's workbench博客园博客,原文链接:http://www.cnblogs.com/alterhu/p/3357420.html,如需转载请自行联系原作者。
<think>我们正在解决如何使用Selenium获取当前页面URL的问题。根据引用内容,特别是引用[1]、[2]、[3]和[4],我们可以明确得知Selenium提供了`driver.current_url`方法来获取当前页面URL。用户的问题直接明确:如何使用Selenium获取当前页面URL?因此,我们只需简洁地回答如何使用这个方法。步骤:1.初始化WebDriver。2.使用`driver.get(url)`访问某个网页。3.使用`driver.current_url`获取当前页面URL。注意:这个方法返回的是字符串形式的当前URL。我们将提供一个简单的示例代码,并说明一些使用场景(比如在测试中断言当前URL是否符合预期)。同时,按照用户要求,在最后提供相关问题。</think> ### 如何在 Selenium获取当前页面 URLSelenium获取当前页面URL 非常简单,通过 `driver.current_url` 属性即可实现。以下是具体方法和使用说明: #### 基本用法 ```python from selenium import webdriver # 启动浏览器并访问页面 driver = webdriver.Chrome() driver.get("https://www.baidu.com") # 获取当前页面URL current_url = driver.current_url print("当前页面URL:", current_url) # 输出:https://www.baidu.com/ # 关闭浏览器 driver.quit() ``` #### 常用场景 1. **验证页面跳转** ```python # 点击链接后验证跳转 driver.find_element(By.LINK_TEXT, "新闻").click() assert driver.current_url == "https://news.baidu.com/", "跳转页面不符合预期" ``` 2. **条件判断** ```python if "login" in driver.current_url: print("当前在登录页面") ``` 3. **结合页面导航** ```python # 获取并记录当前URL start_url = driver.current_url # 执行操作... driver.back() # 返回上一页 # 验证是否返回原页面 assert driver.current_url == start_url, "返回操作失败" ``` #### 注意事项 1. **访问前确保页面加载完成** 在获取 URL 前建议添加等待,避免获取到重定向前的 URL: ```python from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC WebDriverWait(driver, 10).until(EC.url_contains("target_page")) print("当前URL:", driver.current_url) ``` 2. **区分相关属性** - `driver.current_url`:获取当前完整 URL - `driver.title`:获取页面标题 - `driver.page_source`:获取页面 HTML 源码[^1][^3] 3. **特殊字符处理** 当 URL 包含特殊字符时,建议直接使用 `current_url` 进行字符串操作: ```python if "search?q=" in driver.current_url: search_term = driver.current_url.split("=")[1] ``` #### 应用场景 - **自动化测试**:验证页面跳转是否符合预期[^2][^4] - **爬虫开发**:追踪页面访问路径 - **安全审计**:检测 URL 中的敏感参数 - **页面监控**:记录用户浏览路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值