1 re的工作是在python中执行正则表达式 2 import re 3 4 # find 5 result = re.findall('d+', 'baby的电话号是:185123456789') 6 print(result) 7 # 8 it = re.finditer('d+','baby的电话号是:185123456789') 9 for i in it: 10 print(i.group()) # 分组 11 12 # search 搜索, 查找 13 # 一旦匹配到结果. 直接返回, 如果匹配不到结果. 返回None 14 result = re.search('d','baby的电话号是:185123456789') 15 print(result) 16 print(result.group()) 17 # 18 # 19 # match 匹配, 从头开始匹配. 相当于在你正则前面加了一个^ 20 result = re.match('d+','185123456789baby的电话号是:') 21 print(result.group()) 22 23 # search和match的区别: search查找. 找到了结果就返回. match 从头开始匹配 24 25 result = re.finditer(r'姓名:(?P<name>.*?),爱好:(?P<hobby>.*?),', '姓名:宝宝,爱好:女,性格开朗大方') 26 for i in result: 27 print(i.group('name'), i.group('hobby'))
简单爬虫
1 from urllib.request import urlopen 2 3 content = urlopen("https://www.dytt8.net/html/gndy/dyzz/20181219/57954.html").read().decode("gbk") 4 # print(content) 5 6 reg = r'<div id="Zoom">.*?片 名(?P<name>.*?)<br />◎年 代(?P<years>.*?)<br />.*?◎上映日期(?P<date>.*?)<br />'+ 7 '.*?◎主 演(?P<main>.*?)◎简 介.*?<td style="WORD-WRAP: break-word" bgcolor="#fdfddf"><a href="(?P<download>.*?)">' 8 9 it = re.finditer(reg, content, re.S) # re.S 去掉.里面的 10 11 for el in it: 12 print(el.group())