【问题标题】:Behat/Mink - cant find element by xpath with goutteDriverBehat/Mink - 无法使用 goutteDriver 通过 xpath 找到元素
【发布时间】:2015-04-26 02:40:38
【问题描述】:

我正在使用 Behat 3.0 和 Mink 1.6。

这些代码适用于 Selenium2 和 Zombie,但不适用于 Goutte:

    $this->assertSession()->elementTextContains('xpath', "//div[@id='pagecontent-shop']/form/table/tbody/tr[12]/td[2]", $arg1);

    $page = $this->getSession()->getPage();
    $element = $page->find('xpath', "//div[@id='pagecontent-shop']/form/table/tbody/tr[12]/td[2]",)->getText();       

有人知道发生了什么吗?

【问题讨论】:

    标签: selenium-webdriver behat mink zombie.js goutte


    【解决方案1】:

    你试过findById()吗?

    例如

    /**
     * @When /^I click an element with ID "([^"]*)"$/
     *
     * @param $id
     * @throws \Exception
     */
    public function iClickAnElementWithId($id)
    {
        $element = $this->getSession()->getPage()->findById($id);
        if (null === $element) {
            throw new \Exception(sprintf('Could not evaluate element with ID: "%s"', $id));
        }
        $element->click();
    }
    

    例如

    /**
     * Click on the element with the provided css id
     *
     * @Then /^I click on the element with id "([^"]*)"$/
     *
     * @param $elementId ID attribute of an element
     * @throws \InvalidArgumentException
     */
    public function clickElementWithGivenId($elementId)
    {
        $session = $this->getSession();
        $page = $session->getPage();
    
        $element = $page->find('css', '#' . $elementId);
    
        if (null === $element) {
            throw new \InvalidArgumentException(sprintf('Could not evaluate CSS: "%s"', $elementId));
        }
    
        $element->click();
    }
    

    编辑: 下面的示例通过表中的input 元素并找到具有特定name 的元素。不过你需要稍微修改一下。

    /**
     * @Given /^the table contains "([^"]*)"$/
     */
    public function theTableContains($arg1)
    {
        $session = $this->getSession();
        $element = $session->getPage()->findAll('css', 'input');
    
        if (null === $element) {
            throw new \Exception(sprintf('Could not evaluate find select table'));
        }
    
        $options = explode(',', $arg1);
        $match = "element_name";
    
        $found = 0;
        foreach ($element as $inputs) {
            if ($inputs->hasAttribute('name')) {
                if (preg_match('/^'.$match.'(.*)/', $inputs->getAttribute('name')) !== false) {
                    if (in_array($inputs->getValue(), $options)) {
                        $found++;
                    }
                }
            }
        }
    
        if (intval($found) != intval(count($options))) {
            throw new \Exception(sprintf('I only found %i element in the table', $found));
        }
    }
    

    【讨论】:

    • 你好!您的解决方案会很棒,但是如您所见,我的元素在表格内并且没有 id...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2022-07-05
    • 2011-08-14
    • 2019-05-06
    相关资源
    最近更新 更多