Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element by value Selenium/Python

I am using Selenium with Python to automaticlly extract some data from our power plants and right now I need to click on an element. The problem is that the element's xpaths and order change for each plant we are monitoring. The only static info is the value, just like in the 3rd line value="T_U0.

I tried many approaches and I couldn't find a solution. I can't use index or child because the order of the parameters is changing. I tried CSS selector with no success.

Here you get some of my tries...

driver.find_element_by_xpath("//input[@value='T_U0']").click()
driver.find_element_by_css_selector("input[@data-id-sys-abbreviation='388']").click()

I tried many other things but I was just desperately trying anything.

What I really need is a find_by_value, if there is a way of doing it please let me know, if there isn't please show me how I can do it.

I need to click in some options that change order accordingly to the plant

like image 589
Cleyson Shingu Avatar asked May 02 '18 13:05

Cleyson Shingu


People also ask

How do I find an element that contains specific text in Selenium Webdriver Python )?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.

How do you find the value of an element in Selenium?

We can get the value of a HTML input with Selenium webdriver. This is achieved with the help of the getAttribute() method. To retrieve the value of the field with tagname input, we have to pass the value as parameter to the getAttribute() method. Let us consider an html code for a html input.

How do I find an element in Python?

Locate Elements by Tagname This method allows you to find a web-element by specifying the tag name. It will return the first element having the specified name. If the search doesn't succeed, the method will throw the NoSuchElementException. The above code has a title tag with some text.

What is find element by XPath Selenium Python?

You can use XPath to either locate the element in absolute terms (not advised), or relative to an element that does have an id or name attribute. XPath locators can also be used to specify elements via attributes other than id and name.


2 Answers

The problem is with the first xpath. You are trying to locate an input while you need to get option.

Try this:

driver.find_element_by_xpath("//option[@value='T_U0']").click() 
like image 155
Anand Avatar answered Sep 20 '22 17:09

Anand


You can try to click/select element via displayed text. Pseudo code:

driver.find_element_by_xpath("//option[text()="Some text"]").click()
like image 32
Zhivko.Kostadinov Avatar answered Sep 21 '22 17:09

Zhivko.Kostadinov