Python爬虫 教程: re正则表达式解析html页面
生活随笔
收集整理的這篇文章主要介紹了
Python爬虫 教程: re正则表达式解析html页面
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
-
正則表達式(Regular Expression)是一種文本模式,包括普通字符(例如,a 到 z 之間的字母)和特殊字符(稱為"元字符")。
-
正則表達式通常被用來匹配、檢索、替換和分割那些符合某個模式(規(guī)則)的文本。
一、常用正則表達式
單字符:. : 除換行以外所有字符[] :[aoe] [a-w] 匹配集合中任意一個字符\d :數(shù)字 [0-9]\D : 非數(shù)字\w :數(shù)字、字母、下劃線、中文\W : 非\w\s :所有的空白字符包,括空格、制表符、換頁符等等。等價于 [ \f\n\r\t\v]。\S : 非空白數(shù)量修飾:* : 任意多次 >=0+ : 至少1次 >=1? : 可有可無 0次或者1次{m} :固定m次 hello{3,}{m,} :至少m次{m,n} :m-n次邊界:$ : 以某某結(jié)尾 ^ : 以某某開頭分組:(ab) 貪婪模式: .*非貪婪(惰性)模式: .*?re.I : 忽略大小寫re.M :多行匹配re.S :單行匹配re.sub(正則表達式, 替換內(nèi)容, 字符串)練習:
import re#提取出python key="javapythonc++php" re.findall('python',key)[0] # 都有引號#提取出hello world key="<html><h1>hello world<h1></html>" re.findall('<h1>(.*)<h1>',key)[0]#提取170 string = '我喜歡身高為170的女孩' re.findall('\d+',string)#提取出http://和https:// key='http://www.baidu.com and https://boob.com' re.findall('https?://',key)#提取出hello key='lalala<hTml>hello</HtMl>hahah' #輸出<hTml>hello</HtMl> re.findall('<[Hh][Tt][mM][lL]>(.*)</[Hh][Tt][mM][lL]>',key)#提取出hit. key='bobo@hit.edu.com' #想要匹配到hit. re.findall('h.*?\.',key)#匹配sas和saas key='saas and sas and saaas' re.findall('sa{1,2}s',key)#匹配出i開頭的行 string = '''fall in love with you i love you very much i love she i love her'''re.findall('^i.*',string,re.M)#匹配全部行 string1 = """<div>靜夜思 窗前明月光 疑是地上霜 舉頭望明月 低頭思故鄉(xiāng) </div>"""re.findall('.*',string1,re.S)注意:re.findall()通常匹配出來的是列表,所以要通過索引的方式將內(nèi)容提取出來。
二、數(shù)據(jù)解析-正則表達式
1. 需求:爬取糗事百科中所有糗圖照片
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import requests import re import os#創(chuàng)建一個文件夾 if not os.path.exists('./qiutuLibs'): # 注意里面要有引號os.mkdir('./qiutuLibs')headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' }url = 'https://www.qiushibaike.com/pic/' page_text = requests.get(url=url,headers=headers).text#進行數(shù)據(jù)解析(圖片的地址) ex = '<div class="thumb">.*?<img src="(.*?)" alt.*?</div>' #不相關的可以用.*,非貪婪匹配#re.S單行匹配 src_list = re.findall(ex,page_text,re.S) print(src_list)for src in src_list: src = 'https:'+src #發(fā)現(xiàn)src屬性值不是一個完整的url,缺少了協(xié)議頭#對圖片的url單獨發(fā)起請求,獲取圖片數(shù)據(jù).content返回的是二進制類型的響應數(shù)據(jù)img_data = requests.get(url=src,headers=headers).contentimg_name = src.split('/')[-1] # url 最后一個斜杠的就是圖片名img_path = './qiutuLibs/'+img_namewith open(img_path,'wb') as fp:fp.write(img_data)print(img_name,'下載成功!')
2. 糗圖分頁爬取
觀察各個頁面之間的關聯(lián)
輸入1,結(jié)果自動跳轉(zhuǎn)到首頁
注意:url使用format的編寫格式
#封裝一個通用的url模板 url = 'https://www.qiushibaike.com/pic/page/%d/?s=5185803'for page in range(1,36):new_url = format(url%page) #不要忘了format,里面不加引號3. 爬取糗事百科指定頁面的糗圖,并將其保存到指定文件夾中
''' 遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import requests import re import osif __name__ == "__main__":url = 'https://www.qiushibaike.com/pic/%s/'headers={'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',}#指定起始也結(jié)束頁碼page_start = int(input('enter start page:'))page_end = int(input('enter end page:'))#創(chuàng)建文件夾if not os.path.exists('images'):os.mkdir('images')#循環(huán)解析且下載指定頁碼中的圖片數(shù)據(jù)for page in range(page_start,page_end+1):print('正在下載第%d頁圖片'%page)new_url = format(url % page)response = requests.get(url=new_url,headers=headers)#解析response中的圖片鏈接e = '<div class="thumb">.*?<img src="(.*?)".*?>.*?</div>'pa = re.compile(e,re.S)image_urls = pa.findall(response.text)#循環(huán)下載該頁碼下所有的圖片數(shù)據(jù)for image_url in image_urls:image_url = 'https:' + image_urlimage_name = image_url.split('/')[-1]image_path = 'images/'+image_nameimage_data = requests.get(url=image_url,headers=headers).contentwith open(image_path,'wb') as fp:fp.write(image_data)總結(jié)
以上是生活随笔為你收集整理的Python爬虫 教程: re正则表达式解析html页面的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 将字符串作为变量名
- 下一篇: python中的及||