首页 > 解决方案 > Selenium 表搜索未返回正确的文本

问题描述

我目前正在学习如何在 python 中使用 selenium,我有一张表,我想检索元素,但目前遇到了一些麻烦。

<table class="table" id="SearchTable">
  <thead>..</thead>
  <tfoot>..</tfoot>
  <tbody>
    <tr>
      <td class="icon">..</td>
      <td class="title">
         <a class="qtooltip">
           <b>I want to get the text here</b>
         </a>
      </td>
    </tr>

    <tr>
      <td class="icon">..</td>
      <td class="title">
         <a class="qtooltip">
           <b>I want to get the text here as well</b>
         </a>
      </td>
    </tr>
</table>

在这个表中,我想访问粗体标记中的文本,但我的程序没有返回正确的 tr 数,事实上我什至不确定它是否搜索了正确的东西。

我从结尾文本回溯了我的问题,发现错误从带有注释的行开始出现。(我认为之后的代码也是错误的,但我专注于首先获得正确的表格行)

我的代码是:

search_table = driver.find_element_by_id("SearchTable")
search_table_body = search_table.find_element(By.TAG_NAME, "tbody")

trs = search_table_body.find_elements(By.TAG_NAME, "tr")
print(trs) # this does not return correct number of tr)
for tr in trs:
  tds = tr.find_elements(By.TAG_NAME, "td")
  for td in tds:
    href = td.find_element_by_class_name("qtooltip")
    print(href.get_attribute("innerHtml"))

我应该得到正确的 tr 计数,所以我可以返回锚标记中的文本,但我被卡住了。任何帮助表示赞赏。谢谢!

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


您可以使用单个XPath 选择器获取所有<b>标签的子标签,这些<a>标签具有属性qtooltip并位于表格单元格内

//table/descendant::a[@class='qtooltip']/b

示例代码:

elements = driver.find_elements_by_xpath("//table/descendant::a[@class='qtooltip']/b")
for element in elements:
    print(element.text)

演示:

在此处输入图像描述

参考:


推荐阅读