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  括号内的内容




 
 


                

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值