0

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
1
  • what is underscore _ mean? Commented Nov 8, 2018 at 9:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.