如何用正则表达式提取img标签中的src?

时间:2015-11-21 09:09:34

标签: python regex

我试图从HTML img标记中提取图像源网址。

如果html数据如下所示:

<div> My profile <img width='300' height='300' src='http://domain.com/profile.jpg'> </div>

<div> My profile <img width="300" height="300" src="http://domain.com/profile.jpg"> </div>

python中的正则表达式怎么样?

我曾在下面尝试过:

i = re.compile('(?P<src>src=[["[^"]+"][\'[^\']+\']])')
i.search(htmldata)

但我收到了错误

Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

2 个答案:

答案 0 :(得分:9)

BeautifulSoup解析器是可行的方法。

>>> from bs4 import BeautifulSoup
>>> s = '''<div> My profile <img width='300' height='300' src='http://domain.com/profile.jpg'> </div>'''
>>> soup = BeautifulSoup(s, 'html.parser')
>>> img = soup.select('img')
>>> [i['src'] for i in img if  i['src']]
[u'http://domain.com/profile.jpg']
>>> 

答案 1 :(得分:3)

我稍微修改了你的代码。请看一下:

import re

url = """<div> My profile <img width="300" height="300" src="http://domain.com/profile.jpg"> </div>"""
ur11 = """<div> My profile <img width='300' height='300' src='http://domain.com/profile.jpg'> </div>"""

link = re.compile("""src=[\"\'](.+)[\"\']""")

links = link.finditer(url)
for l in links:
    print l.group()
    print l.groups()

links1 = link.finditer(ur11)
for l in links1:
    print l.groups()  

l.groups()中,您可以找到该链接。

输出是这样的:

src="http://domain.com/profile.jpg"
('http://domain.com/profile.jpg',)
('http://domain.com/profile.jpg',)

finditer()是一个生成器,允许使用for in循环。

<强>来源:

http://www.tutorialspoint.com/python/python_reg_expressions.htm

https://docs.python.org/2/howto/regex.html