【问题标题】:Find next/closest button Selenium查找下一个/最近的按钮 Selenium
【发布时间】:2023-03-11 12:45:02
【问题描述】:

我正在使用 selenium 在我的网站上自动填写一些 <input>s。我有多个相同的输入,每个输入都有一个输入字段和一个发送按钮。我想在每个输入字段中发布一个字符串并发送它(该站点不会重新加载)。

input = driver.find_elements_by_class_name('cdRecord')
for in in inputs:
    in.click()
    nr = str(randint(0, 1000))
    in.send_keys("..."+nr)
    NEXT_BUTTON_XPATH = '//button[@type="submit" and @title="next"]' #this does not work
    driver.find_element_by_xpath(NEXT_BUTTON_XPATH).click()

我首先获取所有input,然后对其进行迭代。问题是他填写了每个输入但总是点击同一个按钮。

所以我的问题是,如何找到最近的按钮?

我找到了this,但如果我想使用xpathfollowing-sibling,我还需要获取一些id 并在每次迭代中更改路径,例如:

x = fetch id from the input field?
driver.find_element_by_xpath("//input[@id, "x"]/following-sibling::button")

是否有一个简单的解决方案来找到最接近所选元素的元素?

【问题讨论】:

  • 如果这些INPUTs 在表单中,您只需对表单中的任何元素执行in.submit()
  • @JeffC 不,Ajax 只会在点击我提交时触发,页面会重新加载...

标签: python selenium xpath


【解决方案1】:

您可以使用in.get_attribute('id') 来检索id


或者,您也可以使用 XPath 选择给定元素的 following-sibling::button

in.find_element_by_xpath(".//following-sibling::button").click()

解释:

  • . - 选择当前节点 (<input>)
  • // - 选择文档中的节点
    • following-sibling::button - 当前节点之后的兄弟姐妹是<button>

参考:https://www.w3schools.com/xml/xpath_intro.asp

【讨论】:

  • 非常感谢。第二部分正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
相关资源
最近更新 更多