Gregory
Gregory

Reputation: 315

Invalid or illegal selector while looping through CSS Selector with Selenium

I am attempting to loop through a bunch of rows on a table with Selenium, but am finding that I get an error when attempting to do so. The code should loop through and capture each row in a variable and then compare it against my reference variable, but it throws an error indicating that I've added an invalid or illegal selector.

Please find my code below:

for record in range(35, 2, -1):

        current_record = self.browser.find_element_by_css_selector('#web-body > div > div _
        > div > div > div > div > _
        div:nth-child(2) > div > div > div > div > div > div:nth-child(2) _
        > div.FieldLayout---input_below > div > _
        div.PagingGridLayout---scrollable_content > table _
        > tbody > tr:nth-child(record) > td:nth-child(2) > div > p > a')

        print('the current record is: ' + current_record.text) 
        #print the current record for debugging purposes

        if self.entry_test_id != current_record.text: 
            continue 
            #if the current record in the loop != the correct record, go to the next record

        else:
            web_was_record_found = True #note that record was found for next check

            actions.key_down(Keys.SHIFT).click(current_record).key_up(Keys.SHIFT).perform() 
            #open the found record in a new WINDOW

Upvotes: 0

Views: 353

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

@JimEvans's analysis was in the right direction.

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

So the expression:

for record in range(35, 2, -1)

Will return the sequence of numbers as 35, 34, 33, etc till 2.

So when using the variable record which holds a number from the sequence, to pass it within find_element_by_css_selector() method you need to convert it into string.

So you need to replace the part:

tr:nth-child(record)

As:

tr:nth-child(str(record))

Upvotes: 1

JimEvans
JimEvans

Reputation: 27496

The issue is in your attempt to add your record loop variable to your selector. You’ve used the following (full, convoluted selector omitted for brevity):

'tr:nth-child(record)'

What you really want is something like this:

# Warning: below code might not
# be syntactically correct Python
'tr:nth-child(' + record + ')'

Given this is Python, you should be able to use string formatting to get the term correctly substituted into the selector string. See Python’s documentation for full details of how to do that.

Upvotes: 2

Related Questions