我有一个网页,其中的文本元素有时是链接,有时不是。 所以我需要...
带链接的网页代码
<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.")
检查下面的代码并附上解释:
# 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>.")