您的位置:首页 > 编程语言 > Python开发

Python通过正则表达式和字符串处理获取方式获取所需子字符串的方式

2017-06-14 15:51 591 查看

       在爬虫软件时我们经常需要从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  括号内的内容
                
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐