查找具有相同标记名称的第一个和第二个元素(Python,Selenium)

时间:2018-01-15 21:12:55

标签: python html python-3.x selenium selenium-webdriver

我正在尝试将存储为“points”属性的数据访问自定义“polygon”标记。具体来说,我正在尝试访问有序的点对。

HTML代码:

<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代码:

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)\Google\Chrome\Application\chromedriver.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"))

我的问题似乎是find_element_by_tag_name()不喜欢通常在find_element_by_xpath()中使用的[1]和[2]语法来获取搜索关键字的第一个和第二个实例。当我尝试运行此代码时,我得到一个NoSuchElementException。如果我摆脱[1]和[2]代码将运行,但shape0和shape1都成为第一个多边形元素并打印相同的点,我需要shape1成为第二个多边形元素。有没有办法使用find_element_by_tag_name()来查找具有相同名称的第一个和第二个标记实例?

1 个答案:

答案 0 :(得分:1)

shapes = driver.find_elements_by_tag_name()

注意复数形式的“元素”。这将返回一个带有标签名称的元素列表。