[英]How do I select a web element with no ID through Selenium/Python
I'm trying to select an element on the minehut.com webpage that has no ID. 我试图在minehut.com网页上选择一个没有ID的元素。 Everything I've found says to use a CSS Selector, which hasn't been working
我发现的所有内容都说要使用CSS选择器,但尚未运行
The element I'm trying to select is: 我要选择的元素是:
<button _ngcontent-c17 color="Primary" mat-raised-button class="mat-raised-button mat-primary" style="margin-right: 10px;">
Code: 码:
from selenium import webdriver from selenium.webdriver.common.keys import Keys #Initialize the driver and connect to the website driver = webdriver.Chrome() driver.get('https://minehut.com/panel/login') #Log in driver.find_element_by_id('mat-input-0').send_keys(<Username>) driver.find_element_by_id('mat-input-1').send_keys(<Password> + Keys.RETURN) #Here is the css call for i in driver.find_elements_by_css_selector("button[color='Primary']"): print(i) driver.close()
Ultimately the code will be paired with a discord bot to start/stop a minecraft server (among other server features) This part is attempting to find the Start button, and potentially put it in a variable 最终,代码将与discord bot配对以启动/停止Minecraft服务器(以及其他服务器功能)。该部分试图找到“开始”按钮,并可能将其放入变量中
fixed a syntax error 修复语法错误
replacing driver.find_elements_by_css_selector() with driver.find_elements_by_xpath() works perfectly. 用driver.find_elements_by_xpath()替换driver.find_elements_by_css_selector()效果很好。 The answer explains how to find the xpath of a web element Thanks.
答案解释了如何找到Web元素的xpath谢谢。
有很多方法可以定位元素,xpath,css,id,tagNames,此处在CSS中的外观可能是这样, css= button[color='Primary']
但是,如果还有其他具有相同标识符的按钮,则可能会出现问题。
One potential thing you can try is selecting via the xpath, you can download a chrome extension called xpath finder, and then hover over the desired element to get the xpath, and then attempt to interact with it by doing: 您可以尝试的一种潜在方法是通过xpath进行选择,可以下载一个名为xpath finder的chrome扩展程序,然后将鼠标悬停在所需的元素上以获取xpath,然后尝试通过以下操作与之交互:
driver.find_element_by_xpath(x_path_of_the_element)
I hope that works for you. 希望对您有用。
您可以使用css选择器,更正您的选择器:
driver.find_elements_by_css_selector('button[color="primary"]')
You may have to switch frames if there are multiple frames. 如果有多个框架,则可能必须切换框架。 If not, you can try
driver.find_element_by_xpath(xpath_of_element)
. 如果没有,您可以尝试
driver.find_element_by_xpath(xpath_of_element)
。 In order to get the xpath, you can inspect the element and then right click on the highlighted text in the elements and click Copy>Copy XPath
为了获取xpath,您可以检查元素,然后右键单击元素中突出显示的文本,然后单击
Copy>Copy XPath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.