標籤: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替換殘缺的多網域名稱圖片網址