如何使用javascript selenium获取父div ID?

时间:2017-02-12 00:21:13

标签: javascript html selenium

我正在使用webdriverjs,我想获得webelement的父ID。有多个类叫做row但每个都有不同的id。挑战是在发送消息时生成ID。所以我可以按类抓取innerHtml,然后尝试获取Id。 我有以下的HTML,

<div class="row" id="4003">
<div class="client-chat">
<p class="client-chat-text">If you have any questions, don’t hesitate to message me. I’m here to help with whatever you need!<span class="chat-time">Feb 01 2017 11:30:57</span></p>
</div>
</div>

<div id="4361" class="row">
<div class="coach-chat">
<p class="coach-chat-text">
hi
</p>
</div>

带有id(4361)的第二个div是我需要为我的测试抓取的生成的一个。但是,我可以获取 coach-chat-text 。我如何获得selenium中的父元素。我尝试过以下代码,但我不知道如何获取父ID。

it('send a text message now',function(done){
            driver.findElement(webdriver.By.css("#messageField")).sendKeys('Hi');
            driver.sleep(1000);
            driver.findElement(webdriver.By.xpath(".//*[@id='sendMessage']")).click().then(function(){
                driver.findElement(webdriver.By.className("coach-chat-text")).getText().then(function(text){
                    var message = text.slice(0,2);
                    //i want to fetch the parent id here.
                    try {
                        expect(message).to.equal("www.pluma.co");
                        done();
                    } catch (e) {
                        done(e);
                    }
                });
            });
        });
    });

1 个答案:

答案 0 :(得分:1)

如果您使用webdriver.By.xpath查找带有&#39; coach-chat-text&#39;类的元素,那么您可以使用XPath父选择器 - /parent::node() - 来查找父元素。

如下所示,尽管您的XPath可能会有所不同:

driver.findElement(webdriver.By.xpath(".//*[contains(@class, 'coach-chat-text')]/parent::node()"));

相关问题