如何从python中具有相同后缀的子字符串中提取特定数量的字符



我有这个python代码来从HTML网站中提取图像src

listingid=[img['src'] for img in soup.select('[src]')]

现在想从以下输出中提取值并存储到字典中:

我可以采取什么方法来实现这一点?

我在想,python中是否有任何语法可以在特定后缀(如.jpg(之前使用14个字符

您可以在Python切片中使用负索引从末尾开始计数。既然你在问题中说你想在4个字符的后缀之前有14个字符,那么一个简单的s[-18:-4]就可以了

使用您的代码:

listingid = [img['src'] for img in soup.select('[src]')]
listingid = [s[-18:-4] for s in listingid]

或者,在一句话中:

listingid = [img['src'][-18:-4] for img in soup.select('[src]')]

如果字符数完全相同,请使用切片进行简写,如果不同,我建议按模式尝试split()

[i.get('src').split('_')[-1].split('.')[0] for i in soup.select('[src]')]

或使用regex:

import re
[re.search('.*?([0-9]+).[a-zA-Z]+$',i.get('src')).group(1) for i in soup.select('[src]')]

示例

from bs4 import BeautifulSoup
html = '''
<img src="img/katalog/honda-crv-4x2-2.0-at-2001_30082022103745.jpg">
<img src="img/katalog/mitsubishi-xpander-1.5-exceed-manual-2018_08072022134628.jpg">
'''
soup = BeautifulSoup(html)
[i.get('src').split('_')[-1].split('.')[0] for i in soup.select('[src]')]

输出

['30082022103745', '08072022134628']

最新更新