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

使用Python Selenium抓取动态网站时的XPath元素定位语法问题

解决方案

按解析库分类的正确写法

如果你用的是BeautifulSoup

BeautifulSoup不支持XPath语法(比如//tr/td[2]),换用以下两种方式:

方式1:CSS选择器(推荐)

from bs4 import BeautifulSoup

# 假设soup是已解析好的BeautifulSoup实例
target_tds = soup.select('tr td:nth-of-type(2)')
# 提取文本并生成列表
result = [td.get_text(strip=True) for td in target_tds]

方式2:遍历tr标签

rows = soup.find_all('tr')
result = []
for row in rows:
    tds = row.find_all('td')
    if len(tds) >= 2:
        # 列表索引从0开始,第二个td对应索引1
        result.append(tds[1].get_text(strip=True))

如果你用的是lxml(XPath)

XPath语法//tr/td[2]本身有效,确保解析流程正确:

from lxml import etree

# 假设html是你的网页源码字符串
tree = etree.HTML(html)
# 直接提取td内的文本
target_texts = tree.xpath('//tr/td[2]/text()')
# 过滤空文本并整理为列表
result = [text.strip() for text in target_texts if text.strip()]

额外排查点

  • 若页面tr嵌套在tbody标签内,需调整选择器:
    • CSS选择器改为tbody tr td:nth-of-type(2)
    • XPath改为//tbody/tr/td[2]
  • 如果数据是JS动态渲染的,静态解析库抓不到,需改用Selenium/Playwright等工具模拟浏览器加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:00:02