Python使用Selenium爬取href为#的a标签真实跳转URL问题咨询
针对该场景的可实现方案
核心问题说明
待爬取的a标签没有把真实跳转地址存在href属性里,跳转逻辑是绑定在onclick事件上的前端JS实现,常规取href的方法自然拿不到正确地址。
方案1:零跳转解析参数直出地址(性能最优)
观察目标a标签的onclick属性值toDetailOrUrl(event, '1641438',''),结合手动验证的跳转规则,该站点的详情页路由是固定格式:https://cafe.bithumb.com/view/board-contents/[内容ID],完全不需要触发点击、跳转加载页面,直接解析参数拼接即可得到目标地址。
实现步骤:
- 复用原来的元素定位逻辑,不再取href属性,改为提取onclick的属性值
- 用正则从onclick字符串中提取被单引号包裹的数字内容ID
- 按照固定路由格式拼接目标URL
对应的修改后代码:
import re from selenium import webdriver url = "https://cafe.bithumb.com/view/boards/43" driver = webdriver.Chrome('chromedriver.exe') driver.get(url) driver.implicitly_wait(30) bo = driver.find_element_by_xpath("//tbody[1]/tr[@style='cursor:pointer;border-top:1px solid #dee2e6;background-color: white']/td[2]/a") # 提取onclick属性值 onclick_val = bo.get_attribute('onclick') # 匹配提取数字内容ID content_id = re.search(r"'(\d+)'", onclick_val).group(1) # 拼接得到目标详情页地址 target_detail_url = f"https://cafe.bithumb.com/view/board-contents/{content_id}" print(target_detail_url)
该方法不需要等待页面跳转、不需要加载详情页资源,比模拟点击的效率高80%以上,且不存在元素遮挡、弹窗拦截导致的点击失败问题。
方案2:网络请求拦截获取地址(适配前端逻辑变更场景)
如果担心站点后续修改路由规则,自己拼接的地址不准,可以通过Selenium的性能日志功能监听网络请求,在触发点击后直接抓取跳转的目标URL,不需要等详情页完整加载。
实现步骤:
- 初始化Chrome驱动时开启性能日志捕获能力
- 触发a标签的点击操作(推荐用JS执行点击,减少元素定位报错)
- 从捕获的性能日志中,过滤出包含
board-contents特征的请求地址,即为目标URL
修改后的核心代码片段:
import json from selenium import webdriver from selenium.webdriver.chrome.options import Options # 配置开启性能日志捕获 chrome_options = Options() chrome_options.set_capability("goog:loggingPrefs", {"performance": "ALL"}) driver = webdriver.Chrome("chromedriver.exe", options=chrome_options) driver.get("https://cafe.bithumb.com/view/boards/43") driver.implicitly_wait(30) bo = driver.find_element_by_xpath("//tbody[1]/tr[@style='cursor:pointer;border-top:1px solid #dee2e6;background-color: white']/td[2]/a") # 记录当前窗口句柄 original_handle = driver.current_window_handle # 执行JS点击a标签 driver.execute_script("arguments[0].click();", bo) # 遍历性能日志,匹配详情页请求 target_url = None for log in driver.get_log("performance"): log_message = log.get("message", "") if "board-contents" in log_message: log_data = json.loads(log_message) target_url = log_data["message"]["params"]["request"]["url"] break print(target_url) # 关闭新打开的标签页,切回原列表页 for handle in driver.window_handles: if handle != original_handle: driver.switch_to.window(handle) driver.close() driver.switch_to.window(original_handle)
新手常见踩坑提醒
- 不要触发点击后直接读取
driver.current_url拿地址:如果点击后是新开标签页跳转,驱动默认还停留在原列表页的句柄上,读到的依然是列表页地址,必须先切换到新标签的句柄才行。 - 不要为了拿地址等详情页完全加载:只要匹配到目标请求地址就可以中断流程,能大幅缩短爬取耗时。
- 如果onclick里的方法存在参数加密、动态拼接的情况,方案1就不适用了,直接用方案2的请求拦截方法最稳妥。
内容的提问来源于stack exchange,提问作者rapping_overFlow
相关产品推荐
相关产品推荐

