Home > Net >  How to get the inner text from an <a> tag
How to get the inner text from an <a> tag

Time:04-26

I want to select the Remember Sports part of this line

<a href="https://ww.allmusic.com/artist/remember-sports-mn0003731048">Remember Sports</a>

I can get the href but how do I get the actual text?

This is what I tried, when I tried to pass another argument into get_attribute or leave it blank then it doesn't work.

browser = webdriver.Chrome('c:\\Users\\16308\\Documents\\VSCPython\chromedriver',chrome_options=chrome_options)

url = 'https://www.allmusic.com/album/sunchokes-mw0003322304'
browser.get(url)
stages = browser.find_element_by_class_name('album-artist')
artist_link = stages.find_element_by_css_selector('a').get_attribute('href')
artist_link_text = stages.find_element_by_css_selector('a')
browser.get(artist_link)
print(artist_link_text)

Thanks for any help.

CodePudding user response:

You can try to use .get_attribute("innerHTML"), if it was an input you could also use 'value' instead of innerHTML.

EDIT:

There is another very similar question: Use Python Selenium to get span text

CodePudding user response:

By calling .text you will get the link text value

artist_link_text = stages.find_element_by_css_selector('a').text

CodePudding user response:

Select your element using xpath or css then use get text method to get the text inside:

Text=stages.find_element_by_css_selector('a').text

Or

text=driver.findElement(By.className("Class Locator").getText( );

CodePudding user response:

The text Remember Sports is within the following element:

<h2 >
    <span>
        <a href="https://www.allmusic.com/artist/remember-sports-mn0003731048">Remember Sports</a>            
    </span>
</h2>   

Solution

To extract the text you can use either of the following locator strategies:

  • Using CSS_SELECTOR and get_attribute("innerHTML"):

    print(driver.find_element(By.CSS_SELECTOR, "h2.album-artist a[href^='https://www.allmusic.com/artist']").get_attribute("innerHTML"))
    
  • Using XPATH and text attribute:

    print(driver.find_element(By.XPATH, "//h2[@class='album-artist']//a[@href='https://www.allmusic.com/artist/remember-sports-mn0003731048']").text)
    
  • Related