正則表達式
解釋:符合某個模式(規則)的文本
在線測試工具:https://tool.oschina.net/regex
詳細的正則表達式規則,可見:http://www.runoob.com/python3/python3-reg-expressions.html
re模塊
概述:re爲正則表達式提供了很多api,對正則表達式的使用提供了便利。
修飾符:
1、re.I:忽略大小寫
2、re.M:多行匹配
3、re.S:是.匹配包括換行在內的所有字符
方法:match()
參數:正則表達式,待匹配的字符串,修飾符,返回一個SRE.Match對象
代碼演示:content = 'Hello World Python3.6' pattern = '^\w{5}\s\w{5}\s[p]+\w{5}\d\S\d' result = re.match(pattern,content,re.I) print(result.group())
SRE.Match對象的方法有:
group():返回匹配的內容
span():匹配的範圍
貪婪模式和非貪婪模式
貪婪匹配:.*會匹配儘可能多的字符
非貪婪匹配:格式是.?,或匹配儘可能少的字符
re模塊其他方法
search():和match()類似,但match從字符串開頭就開始匹配,若匹配不到就會返回None,而search則不會;
findall():獲得所有匹配的內容
sub():修改文本
compile():將正則表達式編譯成對象,可重複使用
代碼演示:content = 'birthday:19970704' result = re.sub('\d','5',content)#參數:正則表達式,被替換字符串,被修改文本 print(result)
爬取虎撲網球員得分榜
首先打開虎撲網,切到得分榜頁面:https://nba.hupu.com/stats/players/pts
點擊下一頁,查看得分榜51-100的球員,發現此時鏈接變成:https://nba.hupu.com/stats/players/pts/2 ,多點幾頁就會發現得分榜鏈接的構造是:https://nba.hupu.com/stats/players/pts/ + 頁數
再查看元素(按F12),發現表格的每一行是這麼組成的:
於是就可以寫正則表達式了,需要獲取的內容用括號括起來
代碼如下:import requests import re def get_Page(url): #獲取網頁內容 headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6' } response = requests.get(url,headers=headers) if response.status_code == 200: return response.text else: print('您輸入的網址錯誤!') def parse_page(html): #解析網頁 pattern = '<tr>.*?<td.*?>(.*?)</td>.*?<td.*?><a.*?>(.*?)</a></td>.*?<td.*?><a.*?>(.*?)</a></td>.*?<td.*?>(.*?)</td>.*?' items = re.findall(pattern, html,re.S) # for item in items: # print(item[0],item[1],item[2],item[3]) return items def save(content): with open('nba.txt','a',encoding='utf-8') as f: for item in content: f.writelines(item) f.write('\n') if __name__ == '__main__': #保存前得分榜150名 base_url = 'https://nba.hupu.com/stats/players/pts/' for i in range(1,4): url = base_url + str(i) html = get_Page(url) reslut = parse_page(html) save(reslut)
結果展示: