简体   繁体   中英

Python: How to extract url and decode it?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM