Python Selenium:提取鼠标悬停显示的隐藏按钮链接地址
提取鼠标悬停显示的隐藏按钮链接失败求助
问题说明
我尝试提取鼠标悬停时才显示的隐藏按钮中的跳转链接,但现有代码完全无法找到目标链接。另外未登录状态下无法查看页面完整内容,这可能也是影响因素之一。
相关HTML代码
<div><button type="button" class="ant-btn hover-btn btn-open-detail" ant-click-animating-without-extra-node="false"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg><span>상품정보</span></button><button type="button" class="ant-btn hover-btn btn-generate-link"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg><span>링크 생성</span></button></div>
尝试的Python Selenium代码(执行失败)
prourl = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "/html/body/div[1]/div/div/div[2]/div/div/div[1]/div/div/div[2]/div/div/div/div/div/div/section[3]/div/div[2]/div/div/div/div[1]/div[2]/div[1]/div/button[1]"))) for u in prourl: print(WebDriverWait(u, 10).until(EC.presence_of_element_located((By.TAG_NAME, "a"))).get_attribute('href'))
解决建议
替换脆弱的绝对XPATH:绝对路径极易因页面结构变动失效,改用类名定位目标按钮:
# 定位「상품정보」按钮,可根据需要替换为btn-generate-link target_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "btn-open-detail")))触发鼠标悬停动作:按钮是悬停显示,需先模拟悬停让元素可见:
from selenium.webdriver.common.action_chains import ActionChains # 执行悬停操作 ActionChains(driver).move_to_element(target_button).perform()检查按钮属性而非嵌套a标签:从给出的HTML看,按钮本身是
<button>标签,没有嵌套<a>。跳转链接可能存储在按钮的自定义属性(如data-href)中,或点击后通过JS生成:# 打印按钮完整HTML,查看所有属性 print(target_button.get_attribute('outerHTML')) # 尝试获取可能的链接属性 print(target_button.get_attribute('data-href'))处理登录权限问题:如果页面需要登录才能获取链接,需先模拟登录流程(输入账号密码、提交登录),否则无法访问权限受限的内容。
调整元素等待策略:原代码用
presence_of_all_elements_located获取多个元素,但目标是单个按钮,改用element_to_be_clickable或visibility_of_element_located更精准。
内容的提问来源于stack exchange,提问作者anfwkdrn
相关产品推荐
相关产品推荐

