3

I am creating a program that uses selenium to extract data from a website. In this case I'm trying to get the length of the lesson. I have the following code on a webpage

<li class="">                      
<a href="/academy/lesson/intro-to-personality.html" data-virtual="3">
<span class="lesson__title">Intro to Personality</span></a>
<span class="lessonTime">4:16</span>
</li>

<li class="">                      
<a href="/academy/lesson/intro-to-real-estate.html" data-virtual="3">
<span class="lesson__title">Intro to Real Estate</span></a>
<span class="lessonTime">6:16</span>
</li>

<li class="is-viewing" test-id="course_nav_current_lesson">
<a href="/academy/lesson/freudian-defense-mechanisms.html" data-virtual="3">
Freudian Defense Mechanisms: Definition, Levels & Examples</a>
<span class="lessonTime">7:29</span>
<span class="icon-eye"></span>
</li>

The webpage contains a list of around 8-15 other lessons length's but I'm only interested in the one that the user is assigned. Since it won't visit the same webpage every time the xpath will be dynamic. The only two things that are consistent is the fact that the lesson that the user has been assigned is always at the bottom and the fact that it has a special class called is-viewing. I tried using this code to extract the data:

lessonlength = driver.find_element_by_class_name('lessonTime').get_attribute('innerHTML')
print(f'Lesson is {lessonlength} long')

This returns 4:16 since it's the first element with the same class as the one defined. Is there a way to get the last class found (since it's always at the end).

2 Answers 2

2

Try this one:

result = driver.find_element_by_css_selector(".is-viewing>.lessonTime").text

is-viewing - is unique class and you need its child class named lessonTime

Also, add wait for it to be shown.

Sign up to request clarification or add additional context in comments.

2 Comments

css also has :last-of-type
Yes, in this case it can be avoided.
1

You can find all elements into a list and then loop through the list:

lessonlengthList = driver.find_elements_by_class_name('lessonTime')
for l in lessonlengthList:
    print(f'Lesson is {l.text} long')

or get the last element:

lessonlengthList = driver.find_elements_by_class_name('lessonTime')
print(f'Lesson is {lessonlengthList[-1].get_attribute('innerHTML')} long')

2 Comments

Hmmm the latest statement isn't working for me. For some reason it's picking something in the middle. Is there a way to find it by first calling the parent class is-viewing in this class. Then calling lessonTime?
yes, but that's a larger question. I'd use an xpath like //li[@class="is-viewing"]//span[@class='lessonTime']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.