如何在ChromeDriver中获取按钮的href链接?(Python+最新Selenium)
解决Selenium抓取按钮跳转链接及新标签页切换问题
一、直接提取按钮跳转链接(推荐,避免新标签页操作)
很多跳转按钮的目标链接会藏在属性或JS事件里,不用点击就能直接提取:
- 提取
href属性:如果按钮是<a>标签(很多按钮是a标签伪装的),直接获取href值:button = wd.find_element("xpath", "你的XPATH路径") link = button.get_attribute("href") if link: wd.get(link) - 解析
onclick事件中的链接:如果是<button>标签,跳转逻辑写在onclick里(比如onclick="window.open('https://xxx.com')"),可以提取链接:button = wd.find_element("xpath", "你的XPATH路径") onclick_code = button.get_attribute("onclick") if "window.open" in onclick_code: # 截取引号内的链接内容 start = onclick_code.find("'") + 1 end = onclick_code.find("'", start) link = onclick_code[start:end] wd.get(link) - 检查自定义属性:部分网站会把链接存在
data-href、data-url这类属性里,尝试:link = button.get_attribute("data-href") # 或 link = button.get_attribute("data-url")
二、点击按钮后切换新标签页
如果链接是动态生成的必须点击才能获取,用窗口句柄切换:
# 导入依赖(需提前安装selenium) from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 记录原窗口句柄 original_window = wd.current_window_handle # 点击按钮 button = wd.find_element("xpath", "你的XPATH路径") button.click() # 等待新标签页加载,获取所有窗口句柄 WebDriverWait(wd, 10).until(EC.number_of_windows_to_be(2)) # 遍历找到新窗口句柄 new_window = None for handle in wd.window_handles: if handle != original_window: new_window = handle break # 切换到新标签页 wd.switch_to.window(new_window) # 在这里执行新标签页的操作 # ... # 如需切回原窗口 wd.switch_to.window(original_window)
额外提示
- 确认XPATH定位的是按钮本身,而非内部文本标签(比如
<span>),可以用浏览器F12右键元素复制完整XPATH来定位。 - ChromeDriver只需和你的Chrome浏览器版本匹配,初始化代码示例:
from selenium import webdriver wd = webdriver.Chrome() # 先执行登录操作 wd.get("登录页面URL") # 输入账号密码等步骤 # ...
内容的提问来源于stack exchange,提问作者Roo
相关产品推荐
相关产品推荐

