Find the first and second element with the same tag name (Python, Selenium)

Question:

I’m trying to access data stored as a "points" attribute to a custom "polygon" tag. Specifically, I’m trying to access the ordered pairs of points.

HTML code:

<div class="container text-center" id="game" style="padding-top:100px">
    <p id="score_field">Your score is: 0</p>
    <p></p>
    <span id="shape0" onclick="guess(0,false)" style="padding:25px">
        <svg height="200" width="200">
            <polygon points="200,126.14183666948959 120.31518744339765,50.061801835203006 61.22328848002281,0 0,87.38049800865554 192.31624696476806,200 " style="border: 1px solid #808080" <="" svg=""></polygon>
        </svg>
    </span>
    <span id="shape1" onclick="guess(1,false)" style="padding:25px">
        <svg height="200" width="200">
            <polygon points="200,200 156.72712162408325,0.021254429396077024 83.47573335170307,0 0,74.73287188556839 90.28861349384567,198.61921630042093 " style="border: 1px solid #808080" <="" svg=""></polygon>
        </svg>
    </span>
</div>

Python code for remote access:

from selenium import webdriver
from lxml import html
from selenium.webdriver.common.by import By
import requests

# Creates the webdriver
driver = webdriver.Chrome("C:Program Files (x86)GoogleChromeApplicationchromedriver.exe")
driver.get("https://pick-the-bigger-shape.herokuapp.com/")

# Creates and clicks the button on the website to start the game
python_button = driver.find_elements_by_xpath("//button[@type='button' and @id='start-button' and @class='btn btn-primary']")[0]
python_button.click()

# Finds the polygon elements
shape0 = driver.find_element_by_tag_name("polygon[1]")
shape1 = driver.find_element_by_tag_name("polygon[2]")

# Prints the points attribute of the polygon elements
print (shape0.get_attribute("points"))
print (shape1.get_attribute("points"))

My issue seems to be that find_element_by_tag_name() doesn’t like the [1] and [2] syntax that usually works in find_element_by_xpath() to get the first and second instances of our search key.

When I try to run this code, I get a NoSuchElementException. If I get rid of the [1] and [2], the code will run, but shape0 and shape1 both become the first polygon element and print the same points, and I need shape1 to become the second polygon element. Is there a way to use find_element_by_tag_name() to find the first and second instances of tags that have the same name?

Asked By: Aaron Cao

||

Answers:

shapes = driver.find_elements_by_tag_name()

Note the plural form of “elements”. This will return you a list of elements with the tag name.

Answered By: Jay Winston