繁体   English   中英

Selenium Python - 如何获取深度嵌套的元素

[英]Selenium Python - how to get deeply nested element

我正在探索 Selenium Python 并尝试从 Linkedin 页面获取名称属性以便稍后获取其索引。

这是 HTML:

在此处输入图像描述

这是我尝试这样做的方法:

all_span = driver.find_elements(By.TAG_NAME, "span")

all_span = [s for s in all_span if s.get_attribute("aria-hidden") == "true"]

counter = 1
for i in all_span:
    print(counter)
    print(i.text)
    counter += 1

问题是同一页面上还有其他 span 也具有aria-hidden=true属性,但不相关并且会弄乱索引。

所以我需要达到包含其父 div 之一的名称的跨度,但我不知道如何实现。 查看此处的文档: https://selenium-python.readthedocs.io/locating-elements.html#我似乎无法找到如何定位深度嵌套的元素。

我需要获取 span 元素中的名称。

链接

最好的方法是使用xpath。https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath

假设你有这个:

 <div id="this-div-contains-the-span-i-want"> <span aria-hidden="true"> <.--... //--> </span> </div>

然后,使用 xpath:

xpath = "//div[@id='this-div-contains-the-span-i-want']/span[@aria-hidden='true']"
span_i_want = driver.find_element(By.XPATH, xpath)

因此,在您的示例中,您可以使用:

xpath = "//a[@class='app-aware-link']/span[@dir='ltr']/span[@aria-hidden='true']"
span_i_want = driver.find_element(By.XPATH, xpath)
print(span_i_want.text)

没有错别字但是

print(span_i_want) - returns [] empty array

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM