用python爬虫时re.S的作用

爬虫时遇到这么一个写法:

# 创建正则表达式规则对象,匹配每页里的段子内容,re.S 表示匹配全部字符串内容
pattern = re.compile('<div\sclass="f18 mb20">(.*?)</div>', re.S)

# 将正则匹配对象应用到html源码字符串里,返回这个页面里的所有段子的列表
content_list = pattern.findall(html.decode('gbk'))

看这样一段代码:

import re

a = """sdfkhellolsdlfsdfiooefo:
877898989worldafdsf"""
b = re.findall('hello(.*?)world', a)
c = re.findall('hello(.*?)world', a, re.S)
print('b is ', b)
print('c is ', c)

# b is  []
# c is  ['lsdlfsdfiooefo:\n877898989']

re.S的作用".“下的匹配规则扩展到整个字符串,包括换行符”\n",在正则表达式中,".“的作用是匹配任意字符,”\n"除外,也就是说,它只在一行内匹配,如果有换行那就不行了。而re.S则很好的解决了这一个问题。

现在再来看文章开头的代码,就很简单了:

# 创建正则表达式规则对象,匹配每页里的段子内容,re.S 表示匹配全部字符串内容
pattern = re.compile('<div\sclass="f18 mb20">(.*?)</div>', re.S)

# 将正则匹配对象应用到html源码字符串里,返回这个页面里的所有段子的列表
content_list = pattern.findall(html.decode('gbk'))

使用re.S匹配全文,即整个html,直到找到一个符合条件的div标签才结束。

猜你喜欢

转载自blog.csdn.net/Albert_Ejiestein/article/details/89517516