使用xpath在selenium python中选择文本节点

使用xpath在selenium python中选择文本节点,python,selenium,xpath,Python,Selenium,Xpath,我想用selenium和xpath选择hr节点后面的某些文本。但我一直有一个WebDriverException 以下是我想从中提取文本的html代码: 我想得到的文本是:金融导论。。。商业决策 我使用了以下代码: e = c.find_element_by_xpath("//div[@class='ajaxcourseindentfix']/hr/following-sibling::text()") 问题是我一直在得到这个异常 selenium.common.exceptions.Web

我想用selenium和xpath选择hr节点后面的某些文本。但我一直有一个WebDriverException

以下是我想从中提取文本的html代码:

我想得到的文本是:金融导论。。。商业决策

我使用了以下代码:

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] {}

我该怎么办?

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

我尝试从中实现解决方案,它似乎有效,所以您可以应用以下代码来获得所需的文本节点:

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

HTML有3种类型的节点:元素/属性/文本节点,Selenium的findElement require元素节点作为返回值

在XPath中,
text()
将选择文本节点,这就是为什么会出现该错误

但我们可以使用javascript与文本节点进行交互

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

e=c.通过css\u选择器(“div.ajaxcourseindentfix”)查找元素。getText()
有效吗?使用
div
节点的HTML代码示例更新您的问题text@Naramsim,Python中没有内置的
getText()
方法适用于list
e=c.find\u elements\u by\u css\u选择器(“div.ajaxcourseindentfix”).text
sorry@Naramsim,您仍在尝试从元素列表中获取文本。无论如何,即使应用于单个WebElement
text
属性也应该返回OP想要跳过的
“ACCT 200…”
“Credit hours”
文本节点。。。
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