如何使用 selenium webdriver python 中跨度的定位器打印文本?

How to print the text using a locator from the span in selenium webdriver python?

我正在使用硒进行 UI 测试。我在下面检查 chrome 浏览器的元素。

<div tabindex="-1" unselectable="on" role="gridcell" comp-id="2815" col-id="StartBaseMV" class="ag-cell ag-cell-not-inline-editing ag-cell-with-height cell-number ag-cell-value" style="width: 120px; left: 2020px; text-align: right; ">
  <span>
      <span class="ag-value-change-delta"></span>
      <span class="ag-value-change-value">(,281,158)</span>
  </span>
</div>

我为编写 xpath 所做的尝试。

//div[@col-id="StartBaseMV" and @class="ag-cell ag-cell-not-inline-editing ag-cell-with-height cell-number ag-cell-value"]/span[@class="ag-value-change-data"]/span[@class="ag-value-change-value"]

但是,它不起作用。建议任何线索

由于您要获取的数据存储为文本,您可以使用 text 方法获取它,例如:

driver.find_element_by_class_name('ag-value-change-value').text

如果有多个元素具有相同的 class 名称,那么您可以使用 xpath:

driver.find_element_by_xpath("//div[@col-id='StartBaseMV']//span[@class='ag-value-change-value']").text

您要替换此行:

//div[@col-id="StartBaseMV" and @class="ag-cell ag-cell-not-inline-editing ag-cell-with-height cell-number ag-cell-value"]/span[@class="ag-value-change-data"]/span[@class="ag-value-change-value"]

到这一行:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@col-id='StartBaseMV']//span[@class='ag-value-change-value']")))

您还可以使用 Chrome Xpath 的扩展 Chropath 这里是 link:

https://chrome.google.com/webstore/detail/chropath/ljngjbnaijcbncmcnjfhigebomdlkcjo

当您检查并单击 chropath 时,您将看到所有 xapths

你们非常接近。大概您正在尝试提取文本 ($5,281,158) 并为此需要为 visibility_of_element_located() 引入 WebDriverWait 并且您可以使用以下任一解决方案:

  • 使用CSS_SELECTOR:

    print(WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ag-cell.ag-cell-not-inline-editing.ag-cell-with-height.cell-number.ag-cell-value[col-id='StartBaseMV'] span.ag-value-change-value"))).get_attribute("innerHTML"))
    
  • 使用XPATH:

    print(WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//div[@col-id='StartBaseMV' and @class='ag-cell ag-cell-not-inline-editing ag-cell-with-height cell-number ag-cell-value']//span[@class='ag-value-change-value']"))).get_attribute("innerHTML"))
    
  • 注意:您必须添加以下导入:

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