Reputation: 1971
I am getting response from a API as follows-
def update_csv(products):
print type(products)
print products
[{u'image_url': u'https://external.xx.fbcdn.net/safe_image.php?d=AQBHdbRqB7F6aMKM&url=http%3A%2F%2Fgigya.jp%2Fdpa%2F1.png&cfs=1&_nc_hash=AQDx7P52g0NYBB-3', u'id': u'1411912028843607', u'retailer_id': u'product-1'}, {u'image_url': u'https://external.xx.fbcdn.net/safe_image.php?d=AQDyc-Yyic5QLOqH&url=http%3A%2F%2Fgigya.jp%2Fdpa%2F0.png&cfs=1&_nc_hash=AQDhmhPJxFZEpMFX', u'id': u'993388404100117', u'retailer_id': u'product-0'}, {u'image_url': u'https://external.xx.fbcdn.net/safe_image.php?d=AQB69V2cgASUIci1&url=http%3A%2F%2Fgigya.jp%2Fdpa%2F100.png&cfs=1&_nc_hash=AQAk3eZ4vqWYbOW4', u'id': u'1347112758661660', u'retailer_id': u'product-100'}, {u'image_url': u'https://external.xx.fbcdn.net/safe_image.php?d=AQBM75VZTNuxqaoq&url=http%3A%2F%2Fgigya.jp%2Fdpa%2F10.png&cfs=1&_nc_hash=AQAUdkc6II5eu47D', u'id': u'1358784964179738', u'retailer_id': u'product-10'}]
I want to extract all the urls from this which contains .png
and decode that url
As you can this in the above url it contains http%3A%2F%2Fgigya.jp%2Fdpa%2F1.png
I want to extract all these url and decode and save as a list.
What I tried
image_urls = ""
for product in products:
image_urls += urllib.unquote(product['image_url'].split("=")[2])+"\n"
The problem with this is it doesn't remove "&cfs" form the url
http://gigya.jp/dpa/1.png&cfs
http://gigya.jp/dpa/0.png&cfs
http://gigya.jp/dpa/100.png&cfs
http://gigya.jp/dpa/10.png&cfs
Sorry I new to python. Is there any efficient way to do this? Please help.
Upvotes: 0
Views: 131
Reputation: 174758
Use urlparse
, which makes this a lot simpler:
>>> import urlparse
>>> for i in products:
... print(urlparse.parse_qs(urlparse.urlparse(i['image_url']).query)['url'][0])
...
http://gigya.jp/dpa/1.png
http://gigya.jp/dpa/0.png
http://gigya.jp/dpa/100.png
http://gigya.jp/dpa/10.png
For Python 3, use urllib.parse
:
>>> from urllib.parse import urlparse, parse_qs
>>> for i in products:
... print(parse_qs(urlparse(i['image_url']).query)['url'][0])
...
http://gigya.jp/dpa/1.png
http://gigya.jp/dpa/0.png
http://gigya.jp/dpa/100.png
http://gigya.jp/dpa/10.png
Upvotes: 2