python re库的使用

在爬取网页的过程中,避免不了需要使用正则表达式来获取指定的文字,这时,可以用re库帮忙解决

  • compile方法
    compile方法是用来compile一个正则表达式规则的函数
import re
#简单验证手机号码格式

phone_number_regex = re.compile("^(13\d{9}|14[579]\d{8}|15\d{9}|17[01678]\d{8}|18\d{9})$")
print(phone_number_regex.search("15170020077"))
print(phone_number_regex.search("15779331208"))
print(phone_number_regex.search("15170387252"))

在compile之后,便可以调用compile后的对象的search方法,对指定的字符串进行匹配,以上代码结果如图所示:
在这里插入图片描述
值得注意的是,search方法返回值并不适合用来提取文字,提取文字最好用findall方法,下面会提到

compile之后也可以调用match方法,但是match只从第一个字符开始匹配,如果开头就不匹配,那么匹配失败

match()函数只检测RE是不是在string的开始位置匹配,
search()会扫描整个string查找匹配;
也就是说match()只有在0位置匹配成功的话才有返回,
如果不是开始位置匹配成功的话,match()就返回none。
例如:
print(re.match(‘super’, ‘superstition’).span()) 会返回(0, 5)
而print(re.match(‘super’, ‘insuperable’)) 则返回None
search()会扫描整个字符串并返回第一个成功的匹配
例如:print(re.search(‘super’, ‘superstition’).span())返回(0, 5)
print(re.search(‘super’, ‘insuperable’).span())返回(2, 7)

compile之后还可以调用findall方法,可以找到所有匹配的项

imgSrc = re.findall(findImgSrc, item)[0]

返回的是一个列表,取值的时候要注意添加下标

  • 正则中带小括号的用处,在匹配的正则表达式中返回小括号里面的内容

例如这里的括号,作用是拿到该a标签的地址

findLink = re.compile(r'<a href="(.*)?">')

基本语法
在这里插入图片描述

  • 插一个题外话,如果使用正则表达式不太熟悉的话,也可以用replace()方法除去一些空格和换行之类的东西
number = tds[1].select('div span.pl')[0].string.strip().replace(' ','').replace("\n",'')

使用前:
在这里插入图片描述
使用后:
在这里插入图片描述
再做进一步的优化就行啦

猜你喜欢

转载自blog.csdn.net/weixin_45774350/article/details/108955038