我想在列表中找到以jpg
,png
或类似图片类型结尾的商品。
让我们说这是我的清单:
['http://www.ragalahari.com/index.aspx', 'http://www.ragalahari.com/index.aspx', 'http://www.ragalahari.com/news.aspx', 'http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock1t.jpg', 'http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock2t.jpg', 'http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock3t.jpg', 'http://www.ragalahari.com/images/facebookicon.png', 'http://www.ragalahari.com/images/searchicon.png']
我想找到以jpg
或png
结尾的网址。
我的代码到此为止:
href_links = []
for a in soup.find_all('a', href=True):
href = a.get('href')
href = urljoin(link1, href)
href_links.append(href)
答案 0 :(得分:5)
您可以使用list comprehension和str.endswith
:
images = [x for x in href_links if x.endswith(('jpg', 'png'))]
答案 1 :(得分:2)
您可以使用内置字符串endswith
方法。
your_list = ["http://www.ragalahari.com/index.aspx",
"http://www.ragalahari.com/index.aspx",
"http://www.ragalahari.com/news.aspx",
"http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock1t.jpg",
"http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock2t.jpg",
"http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock3t.jpg",
"http://www.ragalahari.com/images/facebookicon.png",
"http://www.ragalahari.com/images/searchicon.png"]
img_links = []
for a in your_list:
if a.endswith('png') or a.endswith('jpg'):
img_links.append(a)
print img_links
result =
['http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock1t.jpg', 'http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock2t.jpg', 'http://imgcdn.raagalahari.com/feb2015/photosessions/shraddha-das-in-long-black-frock/shraddha-das-in-long-black-frock3t.jpg', 'http://www.ragalahari.com/images/facebookicon.png', 'http://www.ragalahari.com/images/searchicon.png']