【问题标题】:Python Selenium get data with xpath from td inside trPython Selenium 从 tr 内的 td 使用 xpath 获取数据
【发布时间】:2020-10-01 16:30:24
【问题描述】:

我在我的 Python 项目中使用 Selenium,我想使用以下代码获取表中的数据:

xpath = "//div[@id='tab_highscore']//table[contains(@class, 'highscore')]//tr"
users = driver.find_elements_by_xpath(xpath)

for u in users:
    xpath = "//td[@class='name']"
    userTd = u.find_elements_by_xpath(xpath)[0]
    user = userTd.get_attribute('innerText')

    xpath = "//td[@class='score']"
    scoreTd = u.find_elements_by_xpath(xpath)[0]
    score = scoreTd.get_attribute('innerText')

    usersArr.append({"name":user, "ally":ally, "score":score})

在用户和分数中我总是得到第一个 tr 值的问题,知道是什么问题吗?

【问题讨论】:

  • 您正在获取第一个值,因为您是通过索引 [0] 选择它,您可能需要遍历该列表。
  • @Stack 但在循环中,我在tr 中搜索td,u 代表tr
  • 在userId 和scoreId 的xpaths 中添加一个.,所以它分别看起来像这样".//td[@class='name']" 和“.//td[@class='score']”跨度>
  • 没有表格的html代码很难分辨。添加table的html代码

标签: python html python-3.x selenium xpath


【解决方案1】:

您需要在每次迭代中指定指向特定u 的上下文节点(XPath 表达式开头的一个点):

for u in users:
    xpath = ".//td[@class='name']"
    userTd = u.find_element_by_xpath(xpath)
    ...

附:使用find_element_by_xpath(xpath) 代替find_elements_by_xpath(xpath)[0] 和.text 代替.get_attribute('innerText')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多