【问题标题】:How to extract src in img tag with regex?如何使用正则表达式提取 img 标签中的 src?
【发布时间】:2015-11-21 09:09:33
【问题描述】:

我正在尝试从 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'

【问题讨论】:

  • 您是否已经尝试过自己创建正则表达式;这会有所帮助
  • 以上两行代码没有给你那个错误。

标签: python regex


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我稍微修改了您的代码。请看:

    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

    【讨论】:

    • 如果src后面有其他属性就不行了。而且您的小组也无法捕获/:-. 等,这可能是网址的一部分。这是我的模式。 src=[\"\']([a-zA-Z0-9_\.\/\-:]+)[\"\']
    • 肯定有改进的余地。感谢您的意见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2023-03-09
    • 2013-09-10
    • 2010-12-18
    • 2019-01-07
    相关资源
    最近更新 更多