牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2017-06-14 投稿人: 浏览次数:4667

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









                

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。