1. 程式人生 > >python爬蟲三大解析資料方法:正則 及 圖片下載案例

python爬蟲三大解析資料方法:正則 及 圖片下載案例

基本正則用法回顧

# 提取python
key = 'javapythonc++php'
print(re.findall('python', key)[0])

# 提取hello world
key = '<html><h1>hello world</h1></html>'
print(re.findall('<h1>(hello world)</h1>', key)[0])  # 分組的方法

# 提取170
string = '我喜歡cjv170的身高'
print(re.findall('\d+', string)
[0]) # 提取http:// 和 https:// key = 'http://www.baidu.com and https://bjv.com' print(re.findall('https?', key)) # ?值前面一個字元出現過一次或0次 # 提取hit. key = '[email protected]' print(re.findall('h.*?\.', key)) # ?切換貪婪模式 # 提取sas和saas key = 'saas and sas and saaas' print(re.findall('sa{1,2}s', key)) # 匹配i開頭的行 re.S(單行匹配全部拉通) re.M(多行匹配)
string = '''fall in love with you i love you ver much i love she i love her''' print(re.findall('^i.*', string, re.M)) # 匹配全部行 string = '''<div>靜夜思 窗前明月光 低頭思故鄉 </div>''' print(re.findall('<div>.*</div>', string, re.S))

糗事百科 圖片下載案例

import requests
import re

url = 'https://www.qiushibaike.com/pic/'
data = requests.get(url=url).text # re.S單行處理 把換行看成\n一起匹配 img_list = re.findall('<div class="thumb">.*?<img src="//(.*?)".*?>.*?</div>', data, re.S) for url in img_list: img_url = 'https://' + url img_name = url.split('/')[-1] img_data = requests.get(url=img_url).content # 圖片二進位制 with open('糗事百科圖片庫/'+img_name, 'wb') as f: f.write(img_data)