-
-
確定url格式
-
發送請求
-
獲取請求響應
-
解析響應數據,獲取想要數據
-
保存數據(本地文件、數據庫)
2、案例演示:
1、大致程序框架:
# 程序結構 class xxxSpider(object): def __init__(self): # 定義常用變量,url,headers及計數等 def get_html(self): # 獲取響應內容函數,使用隨機User-Agent def parse_html(self): # 使用正則表達式來解析頁面,提取數據 def write_html(self): # 將提取的數據按要求保存,csv、MySQL數據庫等 def main(self): # 主函數,用來控制整體邏輯 if __name__ == '__main__': # 程序開始運行時間戳 start = time.time() spider = xxxSpider() spider.main() # 程序運行結束時間戳 end = time.time() print('執行時間:%.2f' % (end-start))
2、
貓眼電影 - 榜單 - top100榜
電影名稱、主演、上映時間
數據抓取實現
右鍵 - 查看網頁源代碼 - 搜索關鍵字 - 存在!!
-
2、找URL規律
第1頁:https://maoyan.com/board/4?offset=0
第2頁:https://maoyan.com/board/4?offset=10
第n頁:offset=(n-1)*10
-
3、正則表達式
<div class="movie-item-info">.*?title="(.*?)".*?class="star">(.*?)</p>.*?releasetime">(.*?)</p>
-
4、編寫程序框架,完善程序
from urllib import request import re import time import random from fake_useragent import UserAgent class MaoyanSpider(object): def __init__(self): self.url = 'https://maoyan.com/board/4?offset={}' # 計數 self.num = 0 # 獲取 def get_html(self,url): headers = { 'User-Agent' : UserAgent().random } req = request.Request(url=url,headers=headers) res = request.urlopen(req) html = res.read().decode('utf-8') # 直接調用解析函數 self.parse_html(html) # 解析 def parse_html(self,html): re_bds = r'<div class="movie-item-info">.*?title="(.*?)".*?class="star">(.*?)</p>.*?releasetime">(.*?)</p>' pattern = re.compile(re_bds,re.S) # film_list: [('霸王別姬','張國榮','1993'),()] film_list = pattern.findall(html) # 直接調用寫入函數 self.write_html(film_list) def write_html(self,film_list): item = {} for film in film_list: item['name'] = film[0].strip() item['star'] = film[1].strip() item['time'] = film[2].strip()[5:15] print(item) self.num += 1 def main(self): for offset in range(0,31,10): url = self.url.format(offset) self.get_html(url) time.sleep(random.randint(1,2)) print('共抓取數據:',self.num) if __name__ == '__main__': start = time.time() spider = MaoyanSpider() spider.main() end = time.time() print('執行時間:%.2f' % (end-start))
