You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Selenium获取tbody中的所有链接?求助

解决Selenium无法提取whatsmyname.app网站链接的问题

问题根源

  1. 你使用的是绝对XPath,这类路径极易因页面结构微调失效,而且<tbody>本身并不包含href属性——实际链接存在于<tbody>下的<tr>标签内的<a>元素中。
  2. 未等待页面元素完全加载就执行查找操作,导致目标元素还未渲染完成,返回空列表自然没有输出。

修复后的代码示例

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

driver = webdriver.Chrome()
driver.get("https://whatsmyname.app/")

# 显式等待表格行加载完成,最长等待10秒
wait = WebDriverWait(driver, 10)
table_rows = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//table[@id='sitesTable']/tbody/tr")))

# 遍历每行提取链接
for row in table_rows:
    try:
        link_element = row.find_element(By.TAG_NAME, "a")
        href = link_element.get_attribute("href")
        print(href)
    except:
        # 跳过无链接的行(若存在)
        continue

driver.quit()

关键改进点

  • 用显式等待替代直接查找,确保目标元素渲染完成后再执行操作
  • 使用基于表格id的相对XPath定位,比绝对路径更稳定,不易受页面结构小变化影响
  • 直接定位每行内的<a>标签,提取其href属性(这才是实际的目标链接)
  • 加入异常处理,避免因个别行无链接导致脚本中断

内容的提问来源于stack exchange,提问作者Look_thisSTREAMING

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:22:09