在Selenium中找到下一个兄弟元素Python?

2024-04-29 19:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个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的下一个兄弟?


Tags: 代码标记id元素htmldriverbodyone
3条回答

我想纠正马克·罗兰兹的回答,。正确的语法是

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

我们需要将elem传递给一个JavaScript函数并执行它。当我们将elem传递给JS函数时,不能在函数内部使用它的名称,但可以使用^{}。下面是一个如何获得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

使用Xpath:

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

相关问题 更多 >