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

dwbf0jvd  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(135)

我尝试访问存储为自定义“polygon”标记的“points”属性的数据。具体来说,我尝试访问点的有序对。
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()来查找同名标签的第一个和第二个示例?

p3rjfoxz

p3rjfoxz1#

shapes = driver.find_elements_by_tag_name()

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

相关问题