如何使用边缘selenium webdriver和phyton通过文本在级联ID元素的内部查找元素

问题描述 投票:0回答:1

我有一个网页,其中的文本元素有时是链接,有时不是。 所以我需要...

  1. 找到元素
  2. 检查是否是链接
  3. 根据结果执行操作

带链接的网页代码

<span id="UNIQUE_ID">
    <a role="button" class="CLASS_LINK" href="javascript:void(0);" onclick="SOME_CODE">DEFINED_TEXT</a>
</span>

没有链接的网页代码

<span id="UNIQUE_ID">
    <span id="ID" class="CLASS_TEXT" aria-label="SOME_INFO_TEXT">DEFINED_TEXT</span>
</span>
# find text element by ID
txt_element = driver.find_element(By.ID, 'UNIQUE_ID')     # works fine

# now I have to go to the inner part of the cascaded element
inner_part = txt_element.find_element(By.XPATH, "[contains(text(),DEFINED_TEXT)]")    # tried serveral variants, but no one is working

if inner_part.tag_name == 'a':     # perform check, if link
    print("Textelement is Link.")
else:
    print("Textelement is NO Link.")
python-3.x selenium-webdriver microsoft-edge
1个回答
0
投票

检查下面的代码并附上解释:

# Locate the parent <span> with the unique ID
parent_span = driver.find_element(By.ID, 'UNIQUE_ID')

# Check the type of the child element (either <a> or <span>)
child_element = parent_span.find_element(By.XPATH, './*')  # Find the direct child element
tag_name = child_element.tag_name  # Get the tag name of the child element

# Output the result
if tag_name == 'a':
    print("The child element is an <a> tag.")
elif tag_name == 'span':
    print("The child element is a <span> tag.")
else:
    print("The child element is neither <a> nor <span>.")
© www.soinside.com 2019 - 2024. All rights reserved.