使用Selenium获取当前URL失败,尝试StackOverflow方案仍无效
Troubleshooting: Getting Current URL in Selenium Python WebDriver
Hey Bob, let's walk through fixing your issue with getting the current URL in Selenium. First, let's start with the core solution, then cover common pitfalls that might be tripping you up.
The Correct Method to Get Current URL
In Selenium Python, the proper way to retrieve the current browser URL is using the driver.current_url attribute (note the underscore—Python uses snake_case, not camelCase here). I don't see this line in your provided code snippet, so that's probably the first thing to add.
Modified Code Example
Let's expand your code to include the URL retrieval, plus add some best practices like waiting for the page to load:
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # Launch Firefox driver = webdriver.Firefox() url1 = 'https://poshmark.com/search?' driver.get(url1) # Wait for the search box to load to ensure page is ready wait = WebDriverWait(driver, 10) search_box = wait.until(EC.presence_of_element_located((By.ID, "user-search-box"))) # Enter your brand search brand = "freepeople" search_box.send_keys(brand) # You might want to submit the search here, e.g., search_box.submit() # Now get the current URL current_url = driver.current_url print("Current URL:", current_url) # Don't forget to close the driver when done driver.quit()
Common Reasons Your Previous Attempts Failed
- Incorrect Method Name: If you tried
driver.currentUrl(camelCase), that won't work in Python—stick todriver.current_url. - Page Not Fully Loaded: If you tried to get the URL right after
driver.get()without waiting, the page might not have finished loading, leading to unexpected results or errors. UsingWebDriverWaitensures the page is ready before interacting. - Driver/Browser Version Mismatch: Outdated GeckoDriver (for Firefox) or Firefox browser can cause unexpected behavior. Make sure both are updated to compatible versions.
- Elements Not Interactable: If your search input interaction is failing, that might be stopping your code before it gets to the URL retrieval step—adding waits fixes that too.
Give this a shot, and let me know if you still run into issues!
内容的提问来源于stack exchange,提问作者Bob
相关产品推荐
相关产品推荐

