我将以下正则表达式放在一起以从URL中提取图像ID:
''' Parse the post details from the full story page '''
def parsePostFromPermalink(session, permalink):
r = session.get('https://m.facebook.com{0}'.format(permalink))
dom = pq(r.content)
# Parse the images, extract the ID's, and construct large image URL
images = []
for img in dom('a img[src*="jpg"]').items():
if img.attr('src'):
m = re.match(r'/([0-9_]+)n\.jpg/', img.attr('src'))
images.append(m)
return images
网址示例:
https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-0/cp0/e15/q65/s200x200/13645330_275977022775421_8826465145232985957_n.jpg?efg=eyJpIjoiYiJ9&oh=ed5b4593ed9c8b6cfe683f9c6932acc7&oe=57EE1224
我想要这一点:
13645330_275977022775421_8826465145232985957
我已经在regex101上对其进行了测试,并且可以正常工作:https ://regex101.com/r/eS6eS7/2
img.attr('src')
包含正确的URL,并且不为空。我测试了这个。当我尝试使用时m.group(0)
,出现了group
不是函数的异常。m
是None
。
难道我做错了什么?
两个问题:
/.../
不是Python regex语法的一部分search
而不是match
工作示例:
>>> url = "https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-0/cp0/e15/q65/s200x200/13645330_275977022775421_8826465145232985957_n.jpg?efg=eyJpIjoiYiJ9&oh=ed5b4593ed9c8b6cfe683f9c6932acc7&oe=57EE1224"
>>> re.search(r'([0-9_]+)n\.jpg', url).group(0)
'13645330_275977022775421_8826465145232985957_n.jpg'
如果只需要数字部分,请使用此(group(1)
,并注意其他_
):
>>> re.search(r'([0-9_]+)_n\.jpg', url).group(1)
'13645330_275977022775421_8826465145232985957'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句