如何使用Python Selenium提取浏览器地址栏的当前URL?
提取Selenium浏览器当前页面URL的方法
要获取浏览器地址栏的当前URL,直接使用Selenium WebDriver实例的current_url属性即可。需要注意的是,点击按钮后页面可能存在加载延迟,建议添加显式等待确保页面跳转完成,避免拿到跳转前的旧URL。
修改后的完整代码
import pandas as pd from bs4 import BeautifulSoup import requests from urllib.parse import urlparse, urljoin from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 初始化浏览器 browser = webdriver.Chrome() browser.get('https://kadbase.ru') # 输入编号 text_area_xpath = '/html/body/div/div[4]/div[1]/div[1]/div/div[2]/form/div[2]/input[1]' browser.find_element_by_xpath(text_area_xpath).send_keys('45:25:020101:1481') # 点击按钮触发跳转 button_xpath = '/html/body/div/div[4]/div[1]/div[1]/div/div[2]/form/div[2]/input[2]' browser.find_element_by_xpath(button_xpath).click() # 等待页面跳转完成(等待URL与初始页面不同) WebDriverWait(browser, 10).until( EC.url_changes('https://kadbase.ru') ) # 提取并打印当前URL current_url = browser.current_url print("当前页面URL:", current_url) # 关闭浏览器 browser.quit()
关键说明
browser.current_url:直接返回浏览器地址栏的当前URL字符串- 显式等待:通过
WebDriverWait配合url_changes条件,确保页面完成跳转后再提取URL,避免因网络延迟导致获取旧地址 - 冗余优化:你代码中导入的
requests、BeautifulSoup、pandas等库当前未被使用,若后续不需要可删除以精简代码
内容的提问来源于stack exchange,提问作者ya Sheri
相关产品推荐
相关产品推荐

