首页 > 解决方案 > Python + Selenium --How to find a dynamic element

问题描述

I'm a newbie in Selenium. I'm trying to click on an element, HTML structure looks like:

<label>
     <span> text </span>
</label>

I need to click on "text" under <span>, this whole thing is inside another span/div/body etc. and I'm trying to make it dynamic so I can locate it with a different text as well.

And I'm using below code for it:

[...]
vote = input("Which option should I vote for you? :  ")
option = "//label/span[contains(.,'" + vote + "')]\""
option = str(option)
[...]
browser.find_element_by_xpath(option).click()

标签: pythonseleniumselenium-webdriverxpathwebdriver

解决方案


您可以使用 CSS 选择器,但是在不知道 DOM 其余部分的结构的情况下,这可能不够独特,无法可靠地抓取您想要的元素:

find_element_by_css_selector("label span")


推荐阅读