Selenium Python - 获取Web浏览器的当前URL?

时间:2015-11-21 23:31:22

标签: python selenium browser

到目前为止,我有这个:

{{1}}

它一直说第4行"驱动程序"是一种无效的语法。我该如何解决这个问题?

还有一种方法可以让所有当前标签打开,而不只是一个吗?

编辑:上面的代码现在有效;但我有另一个问题!

代码现在打开一个新选项卡,由于某种原因,URL栏有"数据;"在其中,它输出数据;作为印刷品。

但是我希望它能够从已经打开的现有网络浏览器中获取现有的网址,我该如何解决?

2 个答案:

答案 0 :(得分:3)

在Python中,您没有指定Java中所需的变量类型,这是导致错误的原因。同样的错误也会发生,因为您的上一行以String开头。

调用webdriver.Chrome()会返回一个驱动程序对象,因此实际上不需要行webdriver driver = new webdriver()

Python中没有使用new关键字来创建新对象。

试试这个:

from selenium import webdriver

driver = webdriver.Chrome()
url = driver.getCurrentUrl()

答案 1 :(得分:0)

为了从Web驱动程序中提取当前页面的url,您必须调用current_url属性:

from selenium import webdriver
import time

driver = webdriver.Chrome()

#Opens a known doi url
driver.get("https://doi.org/10.1002/rsa.1006")

#Gives the browser a few seconds to process the redirect
time.sleep(3)

#Retrieves the url after the redirect
#In this case https://onlinelibrary.wiley.com/doi/abs/10.1002/rsa.1006
url = driver.current_url 
相关问题