单击使用selenium和xpath的按钮

时间:2015-05-18 20:59:04

标签: php selenium xpath selenium-webdriver

我试图点击名为添加新提醒的按钮:

<div class="text-right">
<a class="btn btn-primary " data-ajaxcom="" href="/admin/person/59139/alerts/add">
<span class="glyphicon glyphicon-plus"></span>
Add new alert
</a>
</div>

以下是我的代码:

    <?php

    // Load up the composer autoloader, which will allow us to use the composer
    // stuff
    require 'vendor/autoload.php';

    $driver = new \Behat\Mink\Driver\Selenium2Driver(
        'firefox', 'base_url'
    );

    // init session:
    $session = new \Behat\Mink\Session($driver);

    // start session:
    $session->start();

    $session->visit('http://www.mywebsite.com/admin');

    $session->wait(400 + rand(0, 100));
    $page = $session->getPage();
    $page->fillField('username', 'admin');
    $page->fillField('password', 'password');
    $page->pressButton('submit');

    $session->visit('http://www.mywebsite.com/admin/person/59139');
    function clickbtnwithxpath($xpath)
        {
            $session = $this->getSession();
            $element = $session->getPage()->find(
                '//a[contains(@class, "btn btn-primary ")]',
                $session->getSelectorsHandler()->selectorToXpath('//a[contains(@class, "btn btn-primary ")]', $xpath)
            );

            // error handling
            if (null === $element) {
                throw new \InvalidArgumentException(sprintf('Could not evaluate XPath: "%s"', $xpath));
            }

            // click button
            $element->click();

        }
?>

它会将我登录并进入警报页面,但不会单击该按钮。我是xpath的新手。我认为这里肯定存在错误。但我做了一个尝试。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果没有id和特定于数据的类,我将依赖于链接文本:

//a[contains(., "Add new alert")]