第2关:图片链接提取※
时间: 2024-01-23 18:14:48 浏览: 8
在Python中,你可以使用正则表达式来提取图片链接。正则表达式是一种强大的模式匹配工具,可以用来在文本中查找特定的模式。
下面是一个示例代码,演示如何使用正则表达式提取图片链接:
```python
import re
def extract_image_links(text):
pattern = r'<img.*?src="(.*?)".*?>'
image_links = re.findall(pattern, text)
return image_links
# 示例文本
text = '<img src="https://example.com/image1.jpg" alt="Image 1"><img src="https://example.com/image2.jpg" alt="Image 2">'
# 提取图片链接
image_links = extract_image_links(text)
# 打印结果
for link in image_links:
print(link)
```
运行以上代码,输出结果为:
```
https://example.com/image1.jpg
https://example.com/image2.jpg
```
在代码中,我们定义了一个`extract_image_links`函数,它接受一个文本参数,并使用正则表达式`<img.*?src="(.*?)".*?>`来匹配图片链接。然后,我们使用`re.findall`函数来找到所有匹配的链接,并将它们存储在一个列表中返回。
你可以将你想要提取图片链接的文本传递给`extract_image_links`函数,并使用返回的链接进行后续操作。