user3595231
user3595231

Reputation: 765

How to dealing with the web element that have a changing "css selector" value in selenium?

In selenium, is there a way I can get the css-selector value by providing the field name?

I am trying to write some selenium cases to fill-in some inputs in the following page. enter image description here

But unfortunately, the elements on this page are neither id nor named. The only way I can reach these fields are by their css-selector values, something as if :

self.driver.find_element_by_css_selector("...")

As at this moment I am looking at this web-page,

the css-selector value of the Local Access Settings area is:

#app > div.app > div > div > div.content > div:nth-child(2) > div > div:nth-child(3) > div.section-title

and the css-selector value of the http text field is :

#app > div.app > div > div > div.content > div:nth-child(2) > div > div:nth-child(3) > div.row > div:nth-child(1) > div > div.col-8.formik-custom-field > div > input[type=text]

But the painful part is, for both css-selector value, its "div:nth-child(3)" part is keep changing. It depends on the inputs on the previous page that leads to the current page. It may be "div:nth-child(4)", "div:nth-child(5)", or even "div:nth-child(6)".

So I was thinking maybe I can find the css-selector value of Local Access Settings string first, and then base on this to concatenate the css-selector string for the http text area.

So the question I have is how may I get the css-selector value if I was providing this "Local Access Settings" keyword in my selenium code ?

Thanks,

Jack

Upvotes: 1

Views: 519

Answers (1)

CatChMeIfUCan
CatChMeIfUCan

Reputation: 569

if the issue is changing CSS by child number like div:nth-child(2) to div:nth-child(3) you can use some loops like this

import itertools 
from selenium.common.exceptions import NoSuchElementException

for i in itertools.count(start=1):
    try:
       self.driver.find_element_by_css_selector("#app > div.app > div > div > div.content > div:nth-child(' + str(i) + ')")
    except NoSuchElementException:
       pass

this will try the child number from 1 to unlimited number and you can add this to every child which is changing use this (' + str(i) + ') on the changing element child number and if the issue is something else please acknowledge me

Upvotes: 1

Related Questions