python3爬虫入门之正则表达式
2018-02-05 09:59
411 查看
本文对正则表达式进行简单的讲解,对于毫无爬虫基础的同学可以5分钟入门。
首先,导入爬虫所需要的re库。
import re.的使用:
#点号表示占位符
a='xz123'
b=re.findall('x.',a)
c=re.findall('x..',a)
print(b)
print(c)
#*号匹配前一个字符0次或无限次
a='xyxy123'
b=re.findall('x*',a)
print(b)
#?号匹配前一个字符0次或1次
a='xz123'
b=re.findall('x?',a)
print(b)
secret_code='hadkfalifexxIxxhfkfkjhjkh134xxlovexx4543367dsaxxyouxx8gffj'
b=re.findall('xx(.*?)xx',secret_code)
print(b)
for each in b:
print(each)
s='''sddfdxxhello
xxhjgjxxworldxxasd'''
s='123ghjjsnak123'
b=re.sub('123(.*?)123','789',s)
print(b)
a='ashgaj47865432578jhbkj657576hkj'
b=re.findall('(\d+)',a)
print(b)
首先,导入爬虫所需要的re库。
import re.的使用:
#点号表示占位符
a='xz123'
b=re.findall('x.',a)
c=re.findall('x..',a)
print(b)
print(c)
['xz'] ['xz1']*的使用:
#*号匹配前一个字符0次或无限次
a='xyxy123'
b=re.findall('x*',a)
print(b)
['x', '', 'x', '', '', '', '', '']?的使用:
#?号匹配前一个字符0次或1次
a='xz123'
b=re.findall('x?',a)
print(b)
['x', '', '', '', '', ''].*的使用:
secret_code='hadkfalifexxIxxhfkfkjhjkh134xxlovexx4543367dsaxxyouxx8gffj'
b=re.findall('xx.*xx',secret_code) print('b',b) c=re.findall('xx.*?xx',secret_code) print('c',c)
b ['xxIxxhfkfkjhjkh134xxlovexx4543367dsaxxyouxx'] c ['xxIxx', 'xxlovexx', 'xxyouxx']括号的使用:
b=re.findall('xx(.*?)xx',secret_code)
print(b)
for each in b:
print(each)
['I', 'love', 'you'] I love you跨行取词:
s='''sddfdxxhello
xxhjgjxxworldxxasd'''
b=re.findall('xx(.*?)xx',s) print('b',b) c=re.findall('xx(.*?)xx',s,re.S) print('c',c)
b ['hjgj'] c ['hello\n', 'world']
对比findall与search的区别
s='sdaxxIxx123xxlovexxjhk' b=re.search('xx(.*?)xx123xx(.*?)xx',s).group(2)#group里的数字小于等于正则表达式中括号数 print('b',b) c=re.findall('xx(.*?)xx123xx(.*?)xx',s) print('c',c) print(type(c)) print(c[0][1])
b love c [('I', 'love')] <class 'list'> lovesub的使用(自动翻页中常用):
s='123ghjjsnak123'
b=re.sub('123(.*?)123','789',s)
print(b)
789纯数字匹配利器:
a='ashgaj47865432578jhbkj657576hkj'
b=re.findall('(\d+)',a)
print(b)
['47865432578', '657576']爬虫中需要用到的基本正则表达式就全部介绍完了。
相关文章推荐
- python 爬虫入门之正则表达式 一
- Python爬虫入门(7):正则表达式
- python3 爬虫入门(三)正则表达式基本使用
- python爬虫入门(2)re模块-正则表达式
- Python爬虫入门(7):正则表达式
- Python爬虫入门七之正则表达式
- Python入门-编写抓取网站图片的爬虫-正则表达式
- Python3爬虫之入门和正则表达式
- Python:入门到实现网络爬虫 Day4 --正则表达式
- python的小实验代码的备份,主要偏向于爬虫方向,难点是正则表达式和编码转换[入门]
- Python爬虫入门七之正则表达式
- Python爬虫入门七之正则表达式
- python3爬虫之入门和正则表达式
- Python爬虫—1入门_4_正则表达式
- 转 Python爬虫入门七之正则表达式
- Python爬虫入门七之正则表达式
- Python3爬虫之入门和正则表达式
- Python3爬虫入门之正则表达式的使用
- python3爬虫之入门和正则表达式
- python3爬虫之入门和正则表达式