一.爬虫数据解析的流程
1.指定url
2.基于requests模块发起请求
3.获取响应中的数据
4.数据解析
5.进行持久化存储
二.解析方法
(1)正则解析
(2)bs4解析
(3)xpath解析
1. 正则解析
常用正则表达式
1 单字符: 2 . : 除换行以外所有字符 3 [] :[aoe] [a-w] 匹配集合中任意一个字符 4 \d :数字 [0-9] 5 \D : 非数字 6 \w :数字、字母、下划线、中文 7 \W : 非\w 8 \s :所有的空白字符包,括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。 9 \S : 非空白 10 数量修饰: 11 * : 任意多次 >=0 12 + : 至少1次 >=1 13 ? : 可有可无 0次或者1次 14 {m} :固定m次 hello{3,} 15 {m,} :至少m次 16 {m,n} :m-n次 17 边界: 18 $ : 以某某结尾 19 ^ : 以某某开头 20 分组: 21 (ab) 22 贪婪模式: .* 23 非贪婪(惰性)模式: .*? 24 25 re.I : 忽略大小写 26 re.M :多行匹配 27 re.S :单行匹配 28 29 re.sub(正则表达式, 替换内容, 字符串)
正则使用练习:
1 import re 2 #提取出python 3 key="javapythonc++php" 4 re.findall('python',key)[0] 5 ##################################################################### 6 #提取出hello world 7 key="<html><h1>hello world<h1></html>" 8 re.findall('<h1>(.*)<h1>',key)[0] 9 ##################################################################### 10 #提取170 11 string = '我喜欢身高为170的女孩' 12 re.findall('\d+',string) 13 ##################################################################### 14 #提取出http://和https:// 15 key='http://www.baidu.com and https://boob.com' 16 re.findall('https?://',key) 17 ##################################################################### 18 #提取出hello 19 key='lalala<hTml>hello</HtMl>hahah' #输出<hTml>hello</HtMl> 20 re.findall('<[Hh][Tt][mM][lL]>(.*)</[Hh][Tt][mM][lL]>',key) 21 ##################################################################### 22 #提取出hit. 23 key='bobo@hit.edu.com'#想要匹配到hit. 24 re.findall('h.*?\.',key) 25 ##################################################################### 26 #匹配sas和saas 27 key='saas and sas and saaas' 28 re.findall('sa{1,2}s',key) 29 ##################################################################### 30 #匹配出i开头的行 31 string = '''fall in love with you 32 i love you very much 33 i love she 34 i love her''' 35 36 re.findall('^.*',string,re.M) 37 ##################################################################### 38 #匹配全部行 39 string1 = """<div>静夜思 40 窗前明月光 41 疑是地上霜 42 举头望明月 43 低头思故乡 44 </div>""" 45 46 re.findall('.*',string1,re.S)
应用: 爬取糗事百科指定页面的糗图,并将其保存到指定文件夹中
1 import requests 2 import re 3 import os 4 if __name__ == "__main__": 5 url = 'https://www.qiushibaike.com/pic/%s/' 6 headers={ 7 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 8 } 9 #指定起始也结束页码 10 page_start = int(input('enter start page:')) 11 page_end = int(input('enter end page:')) 12 13 #创建文件夹 14 if not os.path.exists('images'): 15 os.mkdir('images') 16 #循环解析且下载指定页码中的图片数据 17 for page in range(page_start,page_end+1): 18 print('正在下载第%d页图片'%page) 19 new_url = format(url % page) 20 response = requests.get(url=new_url,headers=headers) 21 22 #解析response中的图片链接 23 e = '<div class="thumb">.*?<img src="(.*?)".*?>.*?</div>' 24 pa = re.compile(e,re.S) 25 image_urls = pa.findall(response.text) 26 #循环下载该页码下所有的图片数据 27 for image_url in image_urls: 2