Blovnar
Blovnar

Reputation: 55

Find a link by href in selenium python

Let's take the example of spotify because I'm listening to music on it right now.

I would like to get the text contained in the href tag in the following code.

<a data-testid="nowplaying-track-link" href="/album/3xIwVbGJuAcovYIhzbLO3J">Toosie Slide</a>

What I want is to get "/album/3xIwVbGJuAcovYIhzbLO3J" or if that's not possible, get "Toosie Slide" in order to store it in a variable to compare it with a constant.

The difficulty with Spotify (and many other sites) is that this href tag is present several times on the web page. So I'd like to get only the link that's contained in "nowplaying-track-link" which is a data-testid.

There, I hope I was clear.

PS: I already know the commands like: driver.find_element_by_xpath, etc... but I can't use them in this case...

Upvotes: 2

Views: 94

Answers (1)

RKelley
RKelley

Reputation: 1119

I'm not sure what you mean about the commands of the type and not being able to use them, but this is how you would get the info you're seeking:

element = driver.find_element_by_css_selector('[data-testid="nowplaying-track-link"]')

href = element.get_attribute('href')

element_text = element.text

if you want to put together the link, you can do it this way:

link = driver.current_url + href

Upvotes: 2

Related Questions