如何在 Selenium Webdriver 2 Python 中获取当前 URL?

244
我想在Selenium中一系列导航后获取当前URL。我知道Ruby有一个叫做getLocation的命令,但是我找不到Python的语法。
我试图在Selenium中进行一系列页面导航后获取当前URL。我知道Ruby有一个名为"getLocation"的命令,但我无法找到Python的语法。请注意,您可以使用HTML标记来格式化文本。

Selenium文档已经解释了一切:https://www.selenium.dev/docs/site/en/webdriver/browser_manipulation/#get-current-url - anandharshan
@anandharshan 这个链接无法使用,请更新一下。 - TipVisor
5个回答

440

使用 current_url 元素用于 Python 2:

print browser.current_url

对于Python 3以及selenium的最新版本:

print(driver.current_url)

175
或者,也被称为driver.current_url - salo.dm
3
假设有一个页面链p1->p2->p3,其中p2基于p1的凭据重定向到p1或p3。如何获得在单击后的URL,我无法理解。Selenium不停留在该页面,并直接给出了p3的URL。如何解决这个问题? - proprius
@proprius https://dev59.com/PZTfa4cB1Zd3GeqPQGfS - ed22
更重要的是,这在 https://selenium-python.readthedocs.io/ 上有文档记录吗? - Robert Johnstone
1
@RobertJohnstone: https://selenium-python.readthedocs.io/api.html?highlight=current_url#selenium.webdriver.remote.webdriver.WebDriver.current_url - xibalba1

97

7

Selenium2Library有一个get_location()方法:

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

2
另一种方法是在Chrome浏览器的URL栏中检查元素的ID,让您的WebDriver点击该元素,然后使用Selenium的“keys common”函数发送用于复制和粘贴的键,并将其打印出来或存储为变量等。 "最初的回答"

0
有多种方法可以通过driver获取当前URL:
driver.current_url
driver.execute_script("return document.URL;")
driver.execute_script("return document.location.href;")
driver.execute_script("return window.location.href;")

(请注意,这里有一些不同的JS变量,具体规定在这里:https://dev59.com/m2435IYBdhLWcg3wfQF9#5388084
在某些情况下,您可能不想要完整的URL,而是想要origin
driver.execute_script("return window.location.origin;")

例如,在stackoverflow页面(比如这个页面),源地址是https://stackoverflow.com。(当你不想要完整的URL时很有用。)
还有一些流行的Python框架,比如SeleniumBase,内置了返回URL(或者源地址)的方法。
self.get_current_url()    # SeleniumBase only
self.get_origin()         # SeleniumBase only

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接