【问题标题】:selecting text node in selenium python with xpath使用 xpath 在 selenium python 中选择文本节点
【发布时间】:2018-07-20 01:28:00
【问题描述】:

我想选择带有 selenium 和 xpath 的 hr 节点之后的某些文本。但我不断收到 WebDriverException

这是我要从中提取文本的 html 代码: html snippet

我想得到的文字是:金融简介...商业决策

我使用了这个代码:

e = c.find_element_by_xpath("//div[@class='ajaxcourseindentfix']/hr/following-sibling::text()")

问题是我不断收到这个异常

selenium.common.exceptions.WebDriverException: Message: TypeError: Expected an element or WindowProxy, got: [object Text] {}

我该怎么办?

【问题讨论】:

  • e = c.find_elements_by_css_selector("div.ajaxcourseindentfix").getText() 有效吗?
  • div节点的HTML代码示例更新为文本
  • @Naramsim , Python 中没有内置的getText() 方法适用于列表
  • e = c.find_elements_by_css_selector("div.ajaxcourseindentfix").text抱歉
  • @Naramsim,您仍在尝试从元素列表中获取文本。无论如何,即使应用于单个 WebElement text 属性也应该返回 OP 想要跳过的 "ACCT 200...""Credit hours" 文本节点......

标签: python selenium xpath


【解决方案1】:

在 selenium 中,您不能使用返回属性或文本节点的 XPath,因此不允许使用 /text() 语法。如果您只想获取特定的子文本节点(节点)而不是完整的文本内容(由text 属性返回),您可能会执行复杂的 JavaScript

我尝试从this question 实施解决方案,它似乎有效,因此您可以应用以下代码来获取所需的文本节点:

driver.execute_script("""var el = document.createElement( 'html' );
                         el.innerHTML = '<div>' + document.querySelector('div.ajaxcourseindentfix').innerHTML.split('<hr>')[1];
                         return el.querySelector( 'div' ).textContent;""")

输出是

Introduction to financial and managerial accounting theory and practice with emphasis on the role of accounting information in business decisions.

【讨论】:

    【解决方案2】:

    HTML 有 3 种类型的节点:Element/Attribute/Text Node,Selenium 的 findElement 需要 Element Node 作为返回值。

    在您的 XPath 中 text() 将选择文本节点,这就是您收到该错误的原因。

    但我们可以使用 javascript 与 Text Node 进行交互。

    script = """
        var text = '';
    
        var childNodes = arguments[0].childNodes; // child nodes includes Element and Text Node
    
        childNodes.forEach(function(it, index){
          if(it.nodeName.toUpperCase() === 'HR') { // iterate until Element Node: hr
            text = childNodes[index+1].textContent; 
            // get the text content of next Child Node of Element Node: hr
          }
        });
        return text;
    """
    ele = driver.find_elements_by_css_selector("div.ajaxcourseindentfix")
    text = driver.execute_script(script, ele)
    print text
    

    【讨论】:

      猜你喜欢
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2018-03-15
      • 2011-05-30
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多