我正在尝试从 HTML img 标签中提取图像源 url。
如果 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'
最佳答案
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']
>>>
关于python - 如何使用正则表达式提取 img 标签中的 src?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33841638/