1. 程式人生 > >Python通過正則表示式和字串處理獲取方式獲取所需子字串的方式

Python通過正則表示式和字串處理獲取方式獲取所需子字串的方式

       在爬蟲軟體時我們經常需要從url中尋找並獲取我們所需要的那一部分內容

此例我們需要從網址new_url= "http://news.sina.com.cn/c/gat/2017-06-14/doc-ifyfzfyz4058260.shtml"中獲取

fyfzfyz4058260

一、字串處理

涉及方法:

                 split()  :字串分割

                 lstrip('doc-i') 從左開始講doc-i內容從字串中移除

                 rstrip('.shtml')從右開始將.shtml從字串中移除

       詳細分佈程式碼講解:
#爬蟲所需url
new_url= "http://news.sina.com.cn/c/gat/2017-06-14/doc-ifyfzfyz4058260.shtml"
#分步驟寫:
arr = new_url.split("/")
print(arr)
#['http:', '', 'news.sina.com.cn', 'c', 'gat', '2017-06-14', 'doc-ifyfzfyz4058260.shtml']
arr = arr[-1]  #取列表最後一個元素
print(arr)
#doc-ifyfzfyz4058260.shtml
newsId = arr.lstrip('doc-i').rstrip('.shtml')
print(newsId) #的得到所需的內容
#fyfzfyz4058260
合併寫法
new_url= "http://news.sina.com.cn/c/gat/2017-06-14/doc-ifyfzfyz4058260.shtml"
newsId = new_url.split("/")[-1].lstrip('doc-i').rstrip('.shtml')
print(newsId)  #fyfzfyz4058260

二、正則表示式寫法

#正則1表示式法
import re
new_url= "http://news.sina.com.cn/c/gat/2017-06-14/doc-ifyfzfyz4058260.shtml"
m = re.search('doc-i(.+).shtml',new_url)
print(m.group(0),m.group(1))
#group(0) doc-ifyfzfyz4058260.shtml 匹配到的內容
#group(1)fyfzfyz4058260  括號內的內容