使用Selenium Python从表(td)读取文本后没有打印任何内容

时间:2016-06-23 13:30:12

标签: python html selenium

我正在尝试打印表格单元格的文本,但没有打印任何内容。它识别元素,但似乎无法找到文本。

HTML看起来像这样:

<tr style="font-weight: 600;">
  <td>
      "
    Available Balance
                                       "
  </td>
  <td id="testBalance" class="text-right ng-binding" style="font-weight:   600;">

                                                         664,265.314
  </td>                                                        

我正试图通过运行来读取(并打印)“664,256.314”的值:

Balance=driver.find_element_by_id("testBalance")
print (Balance.text)

它定位元素,但没有任何内容被打印出来。有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:1)

我认为这只是一个时间问题 - 在您检索它的价值时,余额尚未设置/更新。添加Explicit Wait以等待文本出现:

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

class wait_for_any_text(object):
    def __init__(self, locator, text_):
        self.locator = locator
        self.text = text_

    def __call__(self, driver):
        try:
            element_text = EC._find_element(driver, self.locator).text
            return element_text.strip()
        except StaleElementReferenceException:
            return False

wait = WebDriverWait(driver, 10)
balance = wait.until(wait_for_any_text((By.ID, "testBalance"))) 

print(balance.text)

答案 1 :(得分:0)

(感谢RemcoW)

打印(Balance.get_attribute(&#39;的textContent&#39;))