Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python regular expression to get Image src?

How to use regular expression to get src of image from the following html string using Python

<td width="80" align="center" valign="top"><font style="font-size:85%;font-family:arial,sans-serif"><a href="http://news.google.com/news/url?sa=t&amp;fd=R&amp;usg=AFQjCNFqz8ZCIf6NjgPPiTd2LIrByKYLWA&amp;url=http://www.news.com.au/business/spain-victory-faces-market-test/story-fn7mjon9-1226390697278"><img src="//nt3.ggpht.com/news/tbn/380jt5xHH6l_FM/6.jpg" alt="" border="1" width="80" height="80" /><br /><font size="-2">NEWS.com.au</font></a></font></td>

I tried to use

matches = re.search('@src="([^"]+)"',text)
print(matches[0])

But got nothing

like image 888
Don Li Avatar asked Dec 08 '22 23:12

Don Li


1 Answers

Instead of regex, you could consider using BeautifulSoup:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(junk)
>>> soup.findAll('img')
[<img src="//nt3.ggpht.com/news/tbn/380jt5xHH6l_FM/6.jpg" alt="" border="1" width="80" height="80" />]
>>> soup.findAll('img')[0]['src']
u'//nt3.ggpht.com/news/tbn/380jt5xHH6l_FM/6.jpg'
like image 134
fraxel Avatar answered Dec 29 '22 19:12

fraxel