Get text from html element using selenium

Issue

From the HTML code below I want to get the text of 1 and 2 separately.

<div class="sc-492bf320-0 sc-7d450bff-9 crIwBV juiSXn">
  <div data-change-key="homeScore.display" class="sc-18688171-0 sc-7d450bff-4 fXAhuT fBSHnS">2</div>
  <div data-change-key="awayScore.display" class="sc-18688171-0 sc-7d450bff-4 fXAhuT fBSHnS">1</div>
</div> 
 

Here is my code:

home_score = driver.find_element(By.CSS_SELECTOR,"div.sc-492bf320-0.sc-7d450bff 9.crIwBV.juiSXn")[0].text
away_score = driver.find_element(By.CSS_SELECTOR,"div.sc-492bf320-0.sc-7d450bff 9.crIwBV.juiSXn")[1].text

I am getting an error that TypeError: 'WebElement' object is not subscriptable.

What can I change to get the texts separately?

Solution

You used find_element not find_elements (notice the trailing s). For the former a single WebElement is returned. For the latter, a List of WebElements is returned. A list is a container and is subscriptable (see more here). A WebElement is not a container like List or Tuple. Hence you cannot use the subscriptable notation [int].

Second, div.sc-492bf320-0.sc-7d450bff 9.crIwBV.juiSXn — this CSS selector would fail. It would not give you anything. Remove space before 9 and replace it with a dot (.). More info on using CSS selectors correctly here.

Answered By – Firelord

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published