如何使用Python通过Selenium检索title属性? [英] How to retrieve the title attribute through Selenium using Python?
问题描述
这是我的代码: print(browser.find_element_by_partial_link_text( followers)。get_attributes( title))
。我正在使用 find_element_by_partial_link_text
,因为xpath可能对于每个用户都是唯一的。但是我的代码什么也没返回。这是元素的地址:
This is my code : print(browser.find_element_by_partial_link_text("followers").get_attributes("title"))
. I am using find_element_by_partial_link_text
because maybe the xpath could be unique for each user. But my code returns nothing. This is the element's adress:
<li class=" LH36I">
<a class=" _81NM2" href="/username/followers/">
<span class="g47SY lOXF2" title="3,862,378">3.8m</span>
" followers"
</a>
</li>
所以我的问题是如何使用 find_element_by_partial_link_text获取标题中的值
?
So my question is how can i get the value in the title using find_element_by_partial_link_text
? Thanks in advance.
已解决:您可以看一下DebanjanB的答案。
SOLVED : You can look at DebanjanB 's answer.
推荐答案
标题的文本,即 3,862,378 不在任何< a>
标记之内。因此,您不能使用 find_element_by_partial_link_text()
。此外,该元素是动态元素,因此您必须为所需的 visibility_of_element_located()
引入 WebDriverWait ,然后可以使用以下解决方案:
The text of the title i.e. 3,862,378 isn't within any <a>
tag. Hence you can't use find_element_by_partial_link_text()
. Moreover the element is a dynamic element so so you have to induce WebDriverWait for the desired visibility_of_element_located()
and you can use the following solution:
-
使用
XPATH
:
print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@href='/username/followers/' and contains(., 'followers')]/span"))).get_attribute("title"))
使用 CSS_SELECTOR
:
print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href='/username/followers/']>span"))).get_attribute("title"))
注意:根据文档,实际方法是 get_attribute(name)
而不是 get_attributes()
Note: As per the documentation the actual method is get_attribute(name)
but not get_attributes()
这篇关于如何使用Python通过Selenium检索title属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!