当我打印ID时,它与“检查元素”中的ID不匹配

时间:2019-11-28 15:57:42

标签: python selenium element

我有一个包含以下内容的网页:

<span class="plugin_pagetree_children_span plugin_pagetree_current" id="childrenspan173273808-0"> <a href="/display/Cardians/Shift+Turnover?src=contextnavpagetreemode">Shift Turnover</a> </span>

,我可以使用st = driver.find_element_by_link_text('Shift Turnover')

通过链接文本成功找到它

但是当我使用print('-',st.id)

打印ID时

该ID显示为63cd644e-495b-4985-8f9e-7ea067a2b6f1,而不是childrenspan173273808-0

我也尝试了get_attributeget_property,但是它们都不起作用。欢迎任何提示/技巧/建议。

谢谢。

2 个答案:

答案 0 :(得分:2)

我在这里看到的问题是,您正在尝试获取ID childrenspan173273808-0,但是选择器driver.find_element_by_link_text('Shift Turnover')正在定位没有ID的a元素。这就是get_attribute对您不起作用的原因。您实际上想找到包含所需ID的span元素。

您可以使用它来获取ID childrenspan173273808-0

st = driver.find_element_by_xpath("//span[a[text()='Shift Turnover']]") # locate the span
id = st.get_attribute("id") # get its ID and print
print(id)

此XPath定位出现在span元素之外且文本为a的{​​{1}}元素。我们在包含Shift Turnover元素和span文本的a上进行查询,然后在Shift Turnover元素上调用get_attribute,以检索所需的span ID。

最后-在您的示例中打印出的ID childrenspan173273808-0不是{strong>不是 63cd644e-495b-4985-8f9e-7ea067a2b6f1 ID属性,而是“ the server-assigned opaque ID for the underlying DOM element”。有关详细信息,请参见WebElement上的Selenium文档。

答案 1 :(得分:0)

您正在尝试检索Web元素的值。您需要使用在Web元素界面内部声明的get_attribute方法。基本上,此方法将以字符串格式返回指定属性的值。

解决方案1:

locator= driver.find_element_by_xpath("//span[@id='childrenspan173273808']//a").get_attribute("id")
print(locator)

解决方案2:

locator=driver.find_element_by_xpath("//span[@class='plugin_pagetree_children_span plugin_pagetree_current']//a[1]").get_attribute("id")
print(locator)
相关问题