gpt4 book ai didi

python - 使用 python 检索 selenium 中更新的 url

转载 作者:行者123 更新时间:2023-12-01 08:40:36 25 4
gpt4 key购买 nike

如何使用selenium和Python从firefox浏览器获取更新的url?下面的代码是我正在尝试做的一个非常好的工作示例。该脚本打开一个 URL,在网页中查找搜索栏,粘贴特定产品,然后执行搜索。

我试图在搜索完成后提取更新的网址,该网址应该是https://www.myntra.com/avene-unisex- Thermal-spring-water-50-ml但是我收到 https://www.myntra.com/。如何获取所需的 url?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

firefoxOptions = webdriver.FirefoxOptions()
firefoxOptions.set_preference("dom.webnotifications.enabled", False)

driver = webdriver.Firefox(firefox_options = firefoxOptions)

driver.implicitly_wait(5)

# Maximize the browser window
driver.maximize_window()

# navigate to the home page
driver.get("https://www.myntra.com/")

# Locate the text field to update values
text_field = driver.find_element_by_class_name("desktop-searchBar")

# Clears any value already present in text field
text_field.clear()

# Updates the string in search bar
text_field.send_keys("Avene Unisex Thermal Spring Water 50 ml")
text_field.send_keys(Keys.ENTER)

new_page = driver.current_url
print(new_page)

driver.close()

最佳答案

看来你们已经很接近了。您需要引发WebDriverWait来更改url,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC

    driver=webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
    driver.get("https://www.myntra.com/")
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.desktop-searchBar"))).send_keys("Avene Unisex Thermal Spring Water 50 ml")
    driver.find_element_by_css_selector("a.desktop-submit").click()
    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h1.title-title")))
    print(driver.current_url)
    driver.quit()
  • 控制台输出:

    https://www.myntra.com/avene-unisex-thermal-spring-water-50-ml

关于python - 使用 python 检索 selenium 中更新的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53514793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com