爬蟲抓取網頁來下載小說
阿新 • • 發佈:2018-02-13
程序 rip compile pla ons pos 獲取 except res
利用Python3 編寫爬蟲,從筆趣閣抓個小說下載。
import re import urllib.request import time import easygui as g # 輸入地址 g.msgbox("利用Python3 編寫爬蟲,從筆趣閣抓個小說下載到手機查看") msg = "輸入小說地址,例如http://www.biquge.com.tw/0_213/" title = ‘爬蟲‘ root = g.enterbox(msg,title) # 偽造瀏覽器 headers = {‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 6.1; Win64; x64)‘ ‘AppleWebKit/537.36 (KHTML, like Gecko)‘ ‘ Chrome/62.0.3202.62 Safari/537.36‘} req = urllib.request.Request(url=root, headers=headers) with urllib.request.urlopen(req, timeout=1) as response: # 大部分的涉及小說的網頁都有charset=‘gbk‘,所以使用gbk編碼 htmls = response.read().decode(‘gbk‘) # 匹配所有目錄http://www.biquge.com.tw/0_213/" story_id = root.lstrip("http://www.biquge.com.tw/") dir_req = re.compile(r‘<a href="/%s(\d+?.html)">‘%story_id) dirs = dir_req.findall(htmls) # 創建文件流,將各個章節讀入內存 with open(‘E:\一念永恒.txt‘, ‘w‘) as f: for dir in dirs: # 組合鏈接地址,即各個章節的地址 url = root + dir# 有的時候訪問某個網頁會一直得不到響應,程序就會卡到那裏,我讓他0.6秒後自動超時而拋出異常 while True: try: request = urllib.request.Request(url=url, headers=headers) with urllib.request.urlopen(request, timeout=0.6) as response: html = response.read().decode(‘gbk‘) break except: # 對於抓取到的異常,讓程序停止1.1秒,再循環重新訪問這個鏈接,訪問成功時退出循環 time.sleep(1.1) # 匹配文章標題 title_req = re.compile(r‘<h1>(.+?)</h1>‘) # 匹配文章內容,內容中有換行,所以使flags=re.S content_req = re.compile(r‘<div id="content">(.+?)</div>‘, re.S, ) # 獲取標題 title = title_req.findall(html)[0] # 獲取內容 content_test = content_req.findall(html)[0] # 篩除不需要的的html元素 strc = content_test.replace(‘ ‘, ‘ ‘) content = strc.replace(‘<br />‘, ‘\n‘) print(‘抓取章節>‘ + title) f.write(title + ‘\n‘) f.write(content + ‘\n\n‘)
程序運行圖如下:
爬蟲抓取網頁來下載小說