首页 > 解决方案 > 当子元素使用 selenium 匹配文本时选择父子元素

问题描述

我有这样的html:

<div class="card">
  <div>Foo</div>
  <a>View Item</a>
</div>
<div class="card">
  <div>Bar</div>
  <a>View Item</a>
</div>

我想选择匹配“栏”的卡片,然后单击“查看项目”链接。我试过了

cards = browser.find_elements_by_class_name('card')
for card in cards:
  if card.find_element_by_partial_link_text('Bar'):
     item_anchor = card.find_element_by_partial_link_text('View Item')
     item_anchor.click()

但是我得到了错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Bar"}

标签: pythonselenium

解决方案


There are two ways to handle this situation based on your UI behavior:

1) If UI is fixed, use this xpath to identify and use click() to click on it.

//*[@class='card']/div[.='Bar']/following-sibling::a

2) If you are taking data from any external sources (like Database or Excel), pass your expected value (like Bar or Foo) as a parameter to the xpath method like below:

Define a class called Element like as below:

public class Element {

    private WebElement element;
    private WebDriver driver;
    private String xpath;

//  Constructor will wrap web element into Object and will allow to use any of the method declared below
    public Element(String xpath) {
        this.driver = new ChromeDriver();
        this.xpath = xpath;
        this.element = this.driver.findElement(By.xpath(this.xpath));
    }

    public void click() {
        this.element.click();
    }
}

Create POM class and write a methods like below:

public class PageObjectClass {

        private Element elementToClick(String value) {
            return new Element("//*[@class='card']/div[.='" + value + "']/following-sibling::a");
        }

        public void clickOnViewItemsLink(String value) {
            this.elementToClick(value).click();
        }
    }

By this way, you can click on any of View Item link just by passing value as a parameter

推荐阅读