首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在webElement中生成给定RSelenium的绝对xpath [R]

在webElement中生成给定RSelenium的绝对xpath [R]
EN

Stack Overflow用户
提问于 2019-06-18 01:55:02
回答 2查看 368关注 0票数 1

我正在尝试复制RSelenium:https://stackoverflow.com/a/27611777/7837376中的java在这个答案中所做的工作

我很想做这样的事:

代码语言:javascript
运行
复制
#replicating simple RSelenium process getting all //a elements

library(RSelenium)
#start remDr etc. etc.
all_a <- remDr$findElements(using='xpath','//a')
selected_a <- all_a[[10]]

理想情况下,我可以使用下面的复合函数生成selected_a元素的xpath:

代码语言:javascript
运行
复制
#desired function
getElementXPATH(selected_a) 

我知道可以为相同的元素指定相当多不同的xpath,我只是为元素寻找唯一的xpath标识符,所以元素的任何唯一xpath就足够了!

谢谢!

EN

Stack Overflow用户

发布于 2019-06-18 03:08:48

就我个人而言,我不是一个绝对的xpath粉丝。但是,您可以使用javascript获得绝对xpath,而不是使用您的语言中的函数,这将运行得更快,而且很容易移植。

这是javascript。

代码语言:javascript
运行
复制
// this function will return the absolute xpath of any given element
jsFunction = """window.getAbsoluteXpath =function(el){
    // initialize the variables
    aPath ="";
    // iterate until the tag name is 'HTML'
    while (el.tagName!='HTML'){
        // get parent node
        pEle=el.parentNode;
        // check if there are more than 1 nodes with the same tagname under the parent
        if(pEle.querySelectorAll(el.tagName).length>1){
            //now findout the index of the current child
            cIndex = 0;
            pEle.querySelectorAll(el.tagName).forEach(function(cEle){
               cIndex= cIndex+1;
               // check if iterating ChildNode is equal to current ChildNode
               if(cEle === el){
                 // set the aPath using index
                 aPath = el.tagName + "[" + cIndex + "]" + "/" +aPath;
               }
            })

        }else{
            // simply add the tagName when there is only one child with the tag name
             aPath = el.tagName + "/" +aPath;
        }
        // set parent node as current element
        el=el.parentNode;
    }
    // append HTML to the absolute xpath generated
    return "//HTML/"+aPath.substring(0,aPath.length-1);
};"""

现在,您可以在您感兴趣获得绝对xpath的javascript和pass元素中调用此方法。

让我们尝试获得

堆积如山。

注意:由于我的机器上缺少环境,所以没有测试下面的代码逻辑。

代码语言:javascript
运行
复制
# run the javascript in browser so that you can call the function anytime in your script
remDr %>% executeScript(jsFunction, args = list())

# get stackoverflow `Achievements` link element
webElem <- remDr %>% findElement("css", "a.-link.js-achievements-button")
# # get the absolute xpath of Stackoverflow `Achievements`
remDr %>% executeScript("return getAbsoluteXpath(arguments[0])", args = list(webElem))

屏幕截图:在chrome浏览器控制台中运行javascript以获取证据

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56640816

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档