Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexerror: no such group python

Tags:

python

regex

First of all: I'm feeling really dumb because I know this is a simple question with the answer right under my nose. I have looked answers everywhere but none seems to fit my question.

I am trying to fetch the number of an answer in a page using selenium. This is what I have:

if browser.find_elements_by_css_selector("tr.unreaded"):
print "There's messages unreaded!"
unread_answers = browser.find_elements_by_css_selector("tr.unreaded")
for unread_row in unread_answers:
    row_id = unread_row.get_attribute("id")
    m = re.search('answer_row_\d*', row_id)
    row_number = m.group(1)
    print row_number

This is the peace of HTML document I'm currently looking for:

<tr id="answer_row_3121238" class="bla bla bla">
...
<tr id="answer_row_3121428" class="bla bla bla">
...
<tr id="answer_row_3124238" class="bla bla bla">

I'm getting this error: IndexError: no such group.

I know there is resulted beeing fetched because I tried:

if browser.find_elements_by_css_selector("tr.unreaded"):
print "There's messages unreaded!"
unread_answers = browser.find_elements_by_css_selector("tr.unreaded")
for unread_row in unread_answers:
    row_id = unread_row.get_attribute("id")
    m = re.search('answer_row_\d*', row_id)
    if m:
        print "Fetched results!"
    row_number = m.group(1)
    print row_number

The output was: Fetched results!

Fetched results!

Fetched results!

If I try to:

print m

I get three objects beeing the output.

like image 573
John Meter Avatar asked Feb 27 '16 18:02

John Meter


2 Answers

You haven't used any capturing parentheses in your regex, so there are no groups.

m = re.search('answer_row_(\d+)', row_id)

Also note you should use +, for one or more digits, not *.

like image 68
Daniel Roseman Avatar answered Oct 09 '22 20:10

Daniel Roseman


Because your regex has no groups. Numbered groups are indicated by (...), and named groups are indicated by (?P<...>...). Yours has neither.

like image 35
Ignacio Vazquez-Abrams Avatar answered Oct 09 '22 21:10

Ignacio Vazquez-Abrams