如何在python中获取当前网页的URL?

2024-04-18 01:47:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用selenium并尝试将驱动程序更改为它打开的新页面(同一选项卡) driver.switch\至似乎不起作用,因为我认为它是用来当一个新的窗口打开 driver.current\u网址也似乎不起作用,因为它给了我上一页的网址,我似乎无法找出如何获得当前网页的网址

代码如下:

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


Tags: fromhttpsimportcomsearchyoutubewwwdriver
3条回答

就像Tek Nath说的,你可以增加等待时间,但是你也可以这样做。你知道吗

searchTerm = "unbox therapy"
replaceSpaceWithPlus(searchTerm)
driver.get("https://www.youtube.com/results?search_query=" + searchTerm)

您应该在之前添加一些等待时间 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)

@TekNath的回答是正确的,近乎完美。不过,我建议您在代码中避免使用time.sleep(5),如下所示:

time.sleep(secs) suspends the execution of the current thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

您可以在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
    

相关问题 更多 >