4

正規表現を使用して、Pythonを使用して次のhtml文字列から画像のsrcを取得する方法

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

使ってみました

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

しかし、何も得られませんでした

4

3 に答える 3

9

正規表現の代わりに、 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'
于 2012-06-10T20:33:12.273 に答える
6

正規表現で@を失うだけで、機能します

于 2012-06-10T20:26:00.383 に答える
-1

re少し単純化できます:

match = re.search(r'src="(.*?)"', text)
于 2012-06-10T20:30:07.217 に答える