Python正则表达式从字符串获取所有图像src'

时间:2019-03-19 06:41:22

标签: python regex

如何使用python re获取所有图像src 例如

a = "images src <img src=\"http://aa/6.png\" /> <img src=\"http://aa/7.png\" /> "

我想得到

data = {
'content': 'images src',
'src': ['http://aa/6.png', 'http://aa/7.png']
}

操作方法

2 个答案:

答案 0 :(得分:3)

使用美丽的东西beautifulsoup

from bs4 import BeautifulSoup

a = "images src <img src=\"http://aa/6.png\" /> <img src=\"http://aa/7.png\" /> "
soup = BeautifulSoup(a, 'html.parser')
page_images = [image["src"] for image in soup.findAll("img")]
print(page_images)

因此使用dict存储结果:

from bs4 import BeautifulSoup        
data = {}
a = "images src <img src=\"http://aa/6.png\" /> <img src=\"http://aa/7.png\" /> "
soup = BeautifulSoup(a, 'html.parser')
page_images = [image["src"] for image in soup.findAll("img")]

content = a.split("<")[0]
data['content'] = content
data['src'] = page_images

print(data)

输出

{'content': 'images src ', 'src': ['http://aa/6.png', 'http://aa/7.png']}

但是如果首选正则表达式:

import re

data = {}
a = "images src <img src=\"http://aa/6.png\" /> <img src=\"http://aa/7.png\" /> "
content = a.split("<")[0]

data['content'] = content
if re.search('src="([^"]+)"',a):
  data['src'] = re.findall ('src="(.*?)"', a, re.DOTALL)

print(data)

输出

{'content': 'images src ', 'src': ['http://aa/6.png', 'http://aa/7.png']}

答案 1 :(得分:1)

可以用regex做到:

import re

data = {'content': 'images src',
        'src': re.findall('src="([^"]+)"', a)

输出:

{'content': 'images src', 'src': ['http://aa/6.png', 'http://aa/7.png']}