How to retrieve the title attribute through Selenium using Python?

那年仲夏 提交于 2020-01-09 03:57:44

问题


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>

So my question is how can i get the value in the title using find_element_by_partial_link_text ? Thanks in advance.

SOLVED : You can look at DebanjanB 's answer.


回答1:


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:

  • Using XPATH:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@href='/username/followers/' and contains(., 'followers')]/span"))).get_attribute("title"))
    
  • Using CSS_SELECTOR:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a[href='/username/followers/']>span"))).get_attribute("title"))
    

Note: As per the documentation the actual method is get_attribute(name) but not get_attributes()




回答2:


Use following xpath to get the value.

print(browser.find_element_by_xpath("//a[contains(.,'followers')]/span").get_attribute("title"))



回答3:


Instead you can use xpath like this:

print(browser.find_element_by_xpath("//li[contains(@class,'LH36I')]//a[contains(@class,'_81NM2')]//span[contains(@class,'g47SY lOXF2')]").get_attributes("title"))


来源:https://stackoverflow.com/questions/57708661/how-to-retrieve-the-title-attribute-through-selenium-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!