【问题标题】:Not to able to fetch the text of a div无法获取 div 的文本
【发布时间】:2020-12-18 16:11:11
【问题描述】:
<div _ngcontent-tpr-c123="" class="panel panel--bordered">hac-action: 1: /wae:wae/wae-ha:ha-config/ha-data-sync</div>
old_config_xpath = "//div[contains(text(),'hac-action')]"
element_value = wae_base_params[self.driver_key].find_element_by_xpath(old_config_xpath).text

element_value 为空。

注意:以上 HTML 代码不是网页上可见的内容

【问题讨论】:

  • 能否发完整码?

标签: python selenium dom xpath


【解决方案1】:

任何元素的定位方式都是它在 DOM 上时的位置。

确保元素位于 DOM 上的方法是使用 WebDriverWait 和 expected_conditions:

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


wait = WebDriverWait(browser, 10)

element_value = wait.until(EC.visibility_of_element_located((By.XPATH, "//div[contains(text(),'hac-action')]]"))).text

【讨论】:

    【解决方案2】:

    我没有看到网站的页面源,但是请测试下面的代码,让我知道结果。过去,我使用 get_attribute('innerHTML') 而不是 'text' 并且它工作正常。如果你能告诉我结果,我会很高兴。

    old_config_xpath = "//div[contains(text(),'hac-action')]"
    element_value = wae_base_params[self.driver_key].find_element_by_xpath(old_config_xpath).get_attribute('innerHTML')
    

    【讨论】:

    • 这在某些情况下可以工作,您可以阅读更多 here,正如 OP 在问题中指出的元素不在页面上:因此我的回答...
    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多