python - 当子元素使用 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"}
解决方案
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
推荐阅读
- scanf - 在 scanf() 之后使用 Puts() 和 Gets() 不起作用
- ruby - 如何检查用户输入是否包含数字?在红宝石
- ajax - 无法使用 AJAX 和 AWS API Gateway 发布到 AWS Lambda 函数
- python - AWS API 网关连接到私有端点的 500 错误
- django - 使用诸如“collectstatic”之类的东西填充媒体资产文件
- ruby - Ruby 输出(字符串和整数)
- c++ - 使用 mbedTLS 从服务器中提取公共证书链并存储为字符串
- reactjs - 无法删除屏幕底部的白条
- javascript - 使用 Next.js 和 TS 登录 Facebook SDK
- ios - 调用两个 API 并构建结构 - iOS - Swift