【问题标题】:Find next sibling element in Selenium, Python?在 Selenium,Python 中查找下一个兄弟元素?
【发布时间】:2014-07-16 06:12:07
【问题描述】:

我有这个 HTML:

<body>
    <p id='one'> 1A </p>
    <p id='two'> 2A </p>
    <p id='three'> 3A </p>
    <p id='four'> 4A </p>
    <p id='five'> 5A </p>
    <p id='six'> 6A </p>
    <p id='seven'> 7A </p>
</body>

我使用下面的代码来获取第一个p标签元素:

elem = driver.find_element_by_id('one')

现在,如何找到elem 的下一个兄弟?

【问题讨论】:

标签: python selenium selenium-webdriver


【解决方案1】:

我们需要将elem 传递给一个JavaScript 函数并执行它。当我们将elem 传递给它时,我们不能在JS 函数中使用它的名称,但我们可以使用arguments。下面是一个如何获取elem 的下一个兄弟的示例:

next_sibling = driver.execute_script("""
    return arguments[0].nextElementSibling
""", elem)

看看这个execute_script()函数如何工作的小例子:

sum = driver.execute_script("""
    console.log(arguments[0].innerHTML) // will print innerHTML of the element in console logs of the page
    return arguments[1] + arguments[2]
""", elem, 5, 6)

print(sum) # 11

【讨论】:

  • @user3679414 这应该被认为是正确的答案,因为完全通用,即不需要起点 xpath。刚测试过。 +1
【解决方案2】:

我想纠正 Mark Rowlands 的回答。正确的语法是

driver.find_element_by_xpath("//p[@id='one']/following-sibling::p")

【讨论】:

    【解决方案3】:

    使用 Xpath:

    driver.find_element_by_xpath("//p[@id, 'one']/following-sibling::p")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-15
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 2021-12-17
      相关资源
      最近更新 更多