2013-07-11 31 views

回答

2

這個功能應該做你所需要的。我擴展了@ jh314的迴應,並且使代碼稍微小一點,並檢查url 開始http://imgur.com,因爲該代碼會導致其他URL的問題,例如我所包含的Google搜索。它也只取代了第一例,這可能會導致問題。

def fixImgurLinks(url): 
    if url.lower().startswith("http://imgur.com"): 
     url = url.replace("http://imgur", "http://i.imgur",1) # Only replace the first instance. 
     if not url.endswith(".jpg"): 
      url +=".jpg" 
    return url 

for u in ["http://imgur.com/Cuv9oau","http://www.google.com/search?q=http://imgur"]: 
    print fixImgurLinks(u) 

給出:

>>> http://i.imgur.com/Cuv9oau.jpg 
>>> http://www.google.com/search?q=http://imgur 
+0

感謝每一位,我結束了使用這個版本。有時我仍然會因爲沒有圖片而導致頁面加載錯誤,我點擊了網址,並且顯示頁面未找到或者有些不同。有沒有辦法爲圖像添加檢查,如果找不到,則跳過它 – gallly

+0

該URL最後有一個額外的'/',所以它是一個無效的URL。你可以在轉換過程中檢查URL是否有效,但是你最好問一個新的問題。 – 2013-07-11 03:58:16

+0

謝謝我添加了代碼來刪除它,到目前爲止它一直在工作! – gallly

3

你可以使用一個字符串替換:

s = "http://imgur.com/Cuv9oau" 
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "") 

此設爲s:

'http://i.imgur.com/Cuv9oau.jpg'