如何通过Selenium/Python选择没有ID的web元素

2024-09-30 01:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试选择minehut.com网站没有ID的网页。我找到的所有东西都说使用CSS选择器,但它一直不起作用

我要选择的元素是:

<button _ngcontent-c17 color="Primary" mat-raised-button class="mat-raised-button mat-primary" style="margin-right: 10px;">

代码:

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()

最终,代码将与discord bot配对,以启动/停止minecraft服务器(以及其他服务器功能) 这部分试图找到Start按钮,并可能将其放入变量中

修复了语法错误

你知道吗 更换driver.find_elements_by_css_selector()带driver.find \u元素\u by \u xpath()工作正常。答案解释了如何找到web元素的xpath 谢谢。你知道吗


Tags: thecom元素bydriverbuttonkeysfind
3条回答

有许多方法可以定位元素、xpath、css、id和标记名 下面是它在css中的样子,css= button[color=‘Primary’] 但是,如果有任何其他具有相同标识符的按钮,则可能会出现问题。你知道吗

您可以尝试通过xpath进行选择,您可以下载一个名为xpath finder的chrome扩展,然后将鼠标悬停在所需元素上以获取xpath,然后尝试通过执行以下操作与之交互:

driver.find_element_by_xpath(x_path_of_the_element)

我希望这对你有用。你知道吗

如果有多个帧,可能需要切换帧。如果没有,您可以尝试driver.find_element_by_xpath(xpath_of_element)。为了获得xpath,您可以检查元素,然后右键单击元素中突出显示的文本并单击Copy>Copy XPath

相关问题 更多 >

    热门问题