在爬虫软件时我们经常需要从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 括号内的内容