获取nod下所有文本节点的绝对xpath

2024-04-25 23:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xpath,它是通过添加3个字符串来实现的

path_prefix='(.//tr|.//div[not(ancestor::div)][not(descendant::tr)])[3]'
r1=u'Company  (Name in which such subsidiary conducts business if other than corporate name):  '
path=path=path_prefix+"//*[text()="+"'"+r1+"'"+"]"

当我在浏览器上运行这个路径时,它运行得非常好。但是,当我尝试使用execute_javascript在selenium上运行它时,它会给出一个null元素。在

^{pr2}$

另外,当我运行代码时,我检查了stg元素如下所示。(添加了额外的“\”,但在浏览器中仍然可以完美工作)

stg='var element=document.evaluate("(.//tr|.//div[not(ancestor::div)][not(descendant::tr)])[3]//*[text()=\'Company  (Name in which such subsidiary conducts business if other than corporate name):  \']",document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;return element.getBoundingClientRect()'

编辑:(OP评论)

主要问题是。我想提取html页面中的所有文本节点及其xpath。xpath应该以html///….开头。有没有更好的方法或者已经存在的库。


Tags: pathnameindivwhichprefixnotnull
1条回答
网友
1楼 · 发布于 2024-04-25 23:47:43

如果您想获得html中所有textNode的绝对xpath,我建议使用Javascript会更快、更简单。你只需忽略脚本中的“。在

下面是用python实现的Javascript解决方案。在

注意:数组输出将有“text-absolutexpath”对。在

  # this is the custom javascript developed to get the absolute xpaths for all 
  # textnodes under given element using TreeWalker
  jsFunction = """window.getAbsoluteXpathsUnder =function(el){
  var nText ='';
  var aPath ='';
  var elm="";
  var tNode, aPaths=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(tNode=walk.nextNode()){
        nText = tNode.textContent;
        if (nText.trim()!=""){
        aPath='';
        elm = tNode.parentNode;
        while (elm.tagName!='HTML'){ aPath = elm.tagName + "/" +aPath; elm=elm.parentNode;}
         aPaths.push(nText + " - HTML/" + aPath);
        }
  }
  return aPaths;
};"""
# Run the Javascript function
driver.execute_script(jsFunction)
# get the all text node absolute xpaths under first "div table"
aXpaths = driver.execute_script("return getAbsoluteXpathsUnder(arguments[0])",driver.find_elements_by_css_selector('div table')[0])
print(aXpaths)

这是输出enter image description here

页面中有3个这样的表,可能需要调用aXpaths = driver.execute_script("return getAbsoluteXpathsUnder(arguments[0])",ele)3次或使用循环。在

相关问题 更多 >