【问题标题】:How to get the URL of the current webpage in python?如何在python中获取当前网页的URL?
【发布时间】:2020-04-12 15:45:42
【问题描述】:
我正在使用 selenium,我试图将驱动程序更改为它打开的新页面(相同的选项卡)
driver.switch_to 似乎不起作用,因为我认为它在打开新窗口时使用
driver.current_url 似乎也不起作用,因为它给了我上一页的 url,我似乎不知道如何获取当前页面的 url
代码如下:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver.get("https://www.youtube.com")
searchBar = driver.find_element_by_name("search_query")
searchBar.send_keys("unbox therapy")
searchBar.send_keys(Keys.ENTER)
print(driver.current_url)
这仍然返回https://www.youtube.com
我需要看起来像的搜索查询
https://www.youtube.com/results?search_query=unbox+therapy
【问题讨论】:
标签:
python
selenium
youtube
webdriver
webdriverwait
【解决方案1】:
您应该在之前添加一些等待时间
driver.current_url
因为完全加载网站需要一些时间。加载时间还取决于互联网连接速度和其他因素。对我来说,它无需等待时间就可以工作。
import time
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
driver = webdriver.Chrome("/home/teknath/Desktop/chromedriver")
driver.get("https://www.youtube.com")
searchBar = driver.find_element_by_name("search_query")
searchBar.send_keys("unbox therapy")
searchBar.send_keys(Keys.ENTER)
time.sleep(5)
print(driver.current_url)
【解决方案2】:
就像 Tek Nath 说的,你可以增加等待时间,但你也可以这样做。
searchTerm = "unbox therapy"
replaceSpaceWithPlus(searchTerm)
driver.get("https://www.youtube.com/results?search_query=" + searchTerm)
【解决方案3】:
@TekNath 的答案是正确的,并且接近完美。但是,我建议避免在您的代码中使用 time.sleep(5):
time.sleep(secs) 将当前线程的执行挂起给定的秒数。该参数可以是一个浮点数,以指示更精确的睡眠时间。实际的挂起时间可能少于请求的时间,因为任何捕获的信号都会在执行该信号的捕获例程后终止 sleep()。此外,由于系统中其他活动的调度,暂停时间可能比请求的时间长。
您可以在How to sleep webdriver in python for milliseconds找到详细讨论
作为替代方案,您可以为title_contains() 诱导WebDriverWait,您可以使用以下Locator Strategy:
-
代码块:
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
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://www.youtube.com/")
searchBar = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#search")))
searchBar.send_keys("unbox therapy")
searchBar.send_keys(Keys.ENTER)
WebDriverWait(driver, 10).until(EC.title_contains("unbox therapy"))
print(driver.current_url)
-
控制台输出:
https://www.youtube.com/results?search_query=unbox+therapy