【问题标题】:How to find an element within the parent of an element with Selenium如何使用 Selenium 在元素的父元素中查找元素
【发布时间】:2021-06-07 12:43:36
【问题描述】:

我的目标是通过文本查找元素(在本例中为按钮),然后导航到包含此按钮的 div,然后在该 div 中查找并单击另一个元素(列表标题)。

我的预期结果是程序会在页面中找到一个带有文本“添加到购物车”(如果有的话)的元素,导航到父 div,然后在该 div 中搜索名为“title”的类,然后点击它。实际行为略有不同。该程序将找到一个按钮,导航到其父级,但随后它似乎只是在整个页面中搜索标题元素并选择第一个。

我的问题是:如何只搜索我存储为特定类的变量的 div。

inStockButton = driver.find_element_by_xpath('//button[text()="Add to Basket"]')
inStockButtonParent = inStockButton.find_element_by_xpath('//span/ancestor::div[1]')
productToClick = inStockButtonParent.find_element_by_xpath('//*/div[1]/h3/a')
productToClick.click();

【问题讨论】:

  • 你能显示你的 html 和你想要定位的内容吗?

标签: python selenium xpath


【解决方案1】:

使用相对 xpath:

inStockButton = driver.find_element_by_xpath('//button[text()="Add to Basket"]')
inStockButtonParent = inStockButton.find_element_by_xpath('.//span/ancestor::div[1]')
productToClick = inStockButtonParent.find_element_by_xpath('.//*/div[1]/h3/a')
productToClick.click();

【讨论】:

    【解决方案2】:

    如果您的元素在原始元素的 50 像素范围内,请尝试此操作。

    inStockButton = driver.find_element_by_xpath('//button[text()="添加到购物车"]') driver.find_element_by_xpath('//h3/a').near(inStockButton).click()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2023-04-10
      • 2017-09-12
      • 1970-01-01
      • 2020-02-12
      • 2017-12-03
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多