2

I want to get all my that's inside . I wrote this code:

matchObj = re.search(r'<tr>(.*?)</tr>', txt, re.M|re.I|re.S)

but I only get the first group.

how can I get all groups?

Thanks in advance :)

2
  • Use an HTML parser. Can will never be smarter than the most dumb HTML parser. Commented Dec 11, 2012 at 15:51
  • you should have at least tried "help(re)" match / findall are the basic components of re. Please research a bit before asking on SO> Commented Dec 11, 2012 at 15:52

2 Answers 2

10

findall

matchObj = re.findall(r'<tr>(.*?)</tr>', txt, re.M|re.I|re.S)

search only finds the first one in the given string.

you can read more about the different methods you can use in regex.

however, it looks like you are parsing HTML. why don't you use an HTMl parser?

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

1 Comment

yeah you should use BeautifulSoup or something
5

To get more than one match use re.findall().

However, using regular expressions to parse HTML is going to get ugly and complicated fast. Use a proper HTML parser instead.

Python has several to choose from:

ElementTree example:

from xml.etree import ElementTree

tree = ElementTree.parse('filename.html')
for elem in tree.findall('tr'):
    print ElementTree.tostring(elem)

BeautifulSoup example:

from bs4 import BeautifulSoup

soup = BeautifulSoup(open('filename.html'))
for row in soup.select('table tr'):
    print row

7 Comments

I'd love to learn why my answer is not helpful or wrong; that way I can improve it!
it seems someone did not like us answering this question as we have both been down-voted for no reason.
however both you answered well, I +1'ed both you
Thanks, @MartijnPieters. I've added your notes and example to htmlparsing.com/python.html for future posting.
Author didint ask what to use to find tablerows, he asked how to find them with regex. You gave him answer for finding table and not using regex, how good is your answeR?
|

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.