python替換殘缺的多網域名稱圖片網址

來源:互聯網
上載者:User

標籤:load   使用   操作符   使用字串   一個   滑鼠   erro   代碼   ports   

在擷取網站真是圖片的時候,經常遇到圖片連結殘缺問題。

例如所示的情況:

img標籤中的圖片連結是殘缺的,如果這個網站網域名稱又是多種情況的話,比如  

  http://sports.online.sh.cn/content/2018-03/13/content_8813151.htm

  http://sports.online.sh.cn/images/attachement/jpg/site1/20180313/IMG4ccc6a76b0f047094677984.JPG

  http://shenhua.online.sh.cn/content/2018-03/13/content_8813187.htm

  http://shenhua.online.sh.cn/images/attachement/jpg/site1/20180313/IMGd43d7e5f35354709509383.JPG

 

這兩條新聞是同一個網站的,但是不同的新聞頁面,圖片的連結又是殘缺的,如何擷取真正的圖片連結呢?

首先,我們需要判斷當前頁的網域名稱。將滑鼠移至圖片殘缺url上面就會看到完整的url連結。一般殘缺圖片連結的缺失部分,正是網址欄中的網域名稱部分。

之後,我們就可以在代碼中進行判斷,如:

    def parse_item(self, response, spider):        self.item = self.load_item(response)        if ‘sports‘ in response.url:            self.item[‘content‘] = self.item[‘content‘].replace(‘../../../images‘, ‘http://sports.online.sh.cn/images‘)        elif ‘shenhua‘ in response.url:            self.item[‘content‘] = self.item[‘content‘].replace(‘../../../images‘, ‘http://shenhua.online.sh.cn/images‘)        yield self.item

 

~上面使用成員操作符 in來尋找相應的網域名稱,是較為實用簡單的判斷方法,相同的做用判斷還可以用以下幾種方法來實現:  

~使用string模組的index()/rindex()方法 
index()/rindex()方法跟find()/rfind()方法一樣,只不過找不到子字串的時候會報一個ValueError異常。

import stringdef find_string(s,t):    try:        string.index(s,t)        return True    except(ValueError):         return Falses=‘nihao,shijie‘t=‘nihao‘result = find_string(s,t)print result  #True

 

~使用字串對象的find()/rfind()、index()/rindex()和count()方法

>>> s=‘nihao,shijie‘>>> t=‘nihao‘>>> result = s.find(t)>=0>>> print resultTrue>>> result=s.count(t)>0>>> print resultTrue>>> result=s.index(t)>=0>>> print resultTrue

 

python替換殘缺的多網域名稱圖片網址

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.