【问题标题】:Selenium table search not returning correct textSelenium 表搜索未返回正确的文本
【发布时间】:2019-09-01 13:14:36
【问题描述】:

我目前正在学习如何在 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 计数,以便我可以返回锚标记中的文本,但我被卡住了。任何帮助表示赞赏。谢谢!

【问题讨论】:

    标签: python selenium xpath css-selectors webdriverwait


    【解决方案1】:

    您可以获取所有&lt;a&gt; tag 的子级&lt;b&gt; 标签,这些标签具有qtooltip 的class 属性并使用单个XPath selector 生活在table 单元格中

    //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)
    

    演示:

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      相关资源
      最近更新 更多