Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string operation, extract text between html tags

I have a string:

<font face="ARIAL,HELVETICA" size="-2">  
JUL 28         </font>

(it outputs over two lines, so there must be a \n in there.

I wish to extract the string that's in between the <font></font> tags. In this case, it's JUL 28, but it might be another date or some other number.

1) The best way to extract the value from between the font tags? I was thinking I could extract everything in between "> and </.

edit: second question removed.

like image 936
Flux Capacitor Avatar asked Oct 27 '11 03:10

Flux Capacitor


4 Answers

While it may be possible to parse arbitrary HTML with regular expressions, it's often a death trap. There are great tools out there for parsing HTML, including BeautifulSoup, which is a Python lib that can handle broken as well as good HTML fairly well.

>>> from BeautifulSoup import BeautifulSoup as BSHTML
>>> BS = BSHTML("""
... <font face="ARIAL,HELVETICA" size="-2">  
... JUL 28         </font>"""
... )
>>> BS.font.contents[0].strip()
u'JUL 28'

Then you just need to parse the date:

>>> datetime.strptime(BS.font.contents[0].strip(), '%b %d')
>>> datetime.datetime(1900, 7, 28, 0, 0)
datetime.datetime(1900, 7, 28, 0, 0)
like image 75
kojiro Avatar answered Oct 26 '22 15:10

kojiro


You have a bunch of options here. You could go for an all-out xml parser like lxml, though you seem to want a domain-specific solution. I'd go with a multiline regex:

import re
rex = re.compile(r'<font.*?>(.*?)</font>',re.S|re.M)
...
data = """<font face="ARIAL,HELVETICA" size="-2">  
JUL 28         </font>"""

match = rex.match(data)
if match:
    text = match.groups()[0].strip()

Now that you have text, you can turn it into a date pretty easily:

from datetime import datetime
date = datetime.strptime(text, "%b %d")
like image 45
fahhem Avatar answered Oct 26 '22 14:10

fahhem


Python has a library called HTMLParser. Also see the following question posted in SO which is very similar to what you are looking for:

How can I use the python HTMLParser library to extract data from a specific div tag?

like image 21
yasouser Avatar answered Oct 26 '22 15:10

yasouser


Or, you could simply use Beautiful Soup:

Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping

like image 36
Óscar López Avatar answered Oct 26 '22 15:10

Óscar López